FOR is used in PHP to execute the same code a set number of times. The basic syntax of FOR is as follows:
FOR (expression 1, expression 2, expression 3)
{
[code to execute]
}
FOR tells PHP to first execute "expression 1", then evaluate "expression 2". If "expression 2" is true, then [code to execute] is executed. After this, expression 3 is executed, and then "expression 2" is evaluated again. If "expression 2" is true, then [code to execute] is executed for a second time. The cycle continues until "expression 2" is no longer true.
Let's look at an example. Assuming we have the following piece of code:
FOR ($i = 0; $i <= 2; $i++) { print "value is now " . $i . "<br>"; } |
value is now 0 value is now 1 value is now 2 |
During the 2nd iteration, $i = 1, which means the expression, ($i <= 2), is true. Therefore, the print statement is executed, and $i gets incremented by 1 and becomes 2.
During the 3rd iteration, $i = 2, which means the expression, ($i <= 2), is true. Therefore, the print statement is executed, and $i gets incremented by 1 and becomes 3.
During the 4th iteration, $i = 3, which means the expression, ($i <= 2), is false. Therefore, PHP exits out of the FOR loop, and does not execute the print statement.
DO .. WHILE is used in PHP to provide a control condition. The idea is to execute a piece of code while a condition is true. The basic syntax of DO .. WHILE is as follows:
DO {
[code to execute]
} WHILE (conditional statement)
The difference between DO .. WHILE and WHILE is that DO .. WHILE will always execute the [code to execute] at least once, and in a WHILE construct, it is possible for the [code to execute] to never execute.
Let's look at an example. Assuming we have the following piece of code:
$i = 5 DO { print "value is now " . $i . "<br>"; $i--; } WHILE ($i > 3); |
value is now 5 value is now 4 |
During the 2nd iteration, $i = 4, the print statement is executed, $i gets decreased by 1 and becomes 3, then PHP checks the expression, ($i > 3), which is no longer true. Therefore, PHP exits the loop.
If we change the above code to:
$i = 0 DO { print "value is now " . $i . "<br>"; $i--; } WHILE ($i > 3); |
value is now 0 |
FOREACH is used in PHP to loop over all elements of an array. The basic syntax of FOREACH is as follows:
FOREACH ($array_variable as $value)
{
[code to execute]
}
or
FOREACH ($array_variable as $key => $value)
{
[code to execute]
}
In both cases, the number of times [code to execute] will be executed is equal to the number of elements in the $array_variable array.
Let's look at an example. Assuming we have the following piece of code:
$array1 = array(1,2,3,4,5); FOREACH ($array1 as $abc) { print "new value is " . $abc*10 . "<br>"; } |
new value is 10 new value is 20 new value is 30 new value is 40 new value is 50 |
Previous Page->PHP-while-loop || Next Page->PHP-Include