Loops in php

A loop in php is used to execute a single block statement more than once. That means it is used to execute a piece of code for a number of times or repeatedly.

The following are the 4 types of looping statements available in PHP.

1.for
2.while
3.do...while
4.foreach

1.for loop

The for loop is the loop which checks the condition firstly and then only execute the following looping block. Therefore we can say that for loop is more efficient than other loops. The loop will repeatedly execute the statement untill certain conditions are met. Ut is an entry controlled loop.

Syntax:

for(intialization;test_expression;updation)
{
//Body of for loop
}



2.while loop


The while loop is also an entry controlled loop since it checks the condition at the beginning of the loop. The while loop executes a block of code asa long as the specified condition is true.

Syntax:

while(condition)
{
//Code to be executed
}

3.do...while loop


The do...while loop is an exit controlled loop because it checks its condition after executing the block of code. It is less efficient than other loops since it is an exit controlled loop. The do...while loop will always execute the block of code atleast once. And repeat the block untill the condition is true.

Syntax:

do
{
//
Code to be executed
}
while(condition);

4.foreach loop


The foreach loop is also an entry controlled loop. The difference between foreach loop and other loop is that foreach loop works only on arrays and is used to loop through each key or value pair in an array.

Syntax:

foreach($array as $value)
{
//Code to be executed
}


Prev
Next

Comments

Popular posts from this blog

Node.js Cheat Sheet

Codeigniter ! Simple But Powerful

Bootstrap ? What is it ?