PHP loops are similar to those of other high-level languages. They allow statements to repeatedly executed as long as a conditional expression remains true.
The loop statements that PHP offers are while, do ... while, for and foreach which is only used with arrays.
The while Loop
This loop structure repeats one or more statements as long as a condition remains true. The condition is checked first so if the condition is initially false the statements will never be executed.
Obviously the loop must contain a statement that allows the condition to become true at some point or the loop will never end.
The only difference between this and the while loop is that the condition is checked at the end of the loop therefore the statements enclosed will always be executed at least once.
Again the loop must contain a statement that allows the condition to become true at some point or the loop will never end.
Example of a do ... while Loop
<?php
$var = 1;
do
{
echo($var . " ");
$var ++;
} while ($var < 20)
?>
The for Loop
The for loop is designed to iterate a set number of times. It has three parts separated by semicolons.
The initial statement(s). This sets up the initial counter(s) and is executed only once, before the loop body is executed.
The loop condition. This is a conditional expression that is evaluated, normally to see if the loop limit(s) has been reached, before the start of each loop - if it returns false the loop body is not executed.
the end loop statement(s). This updates the counter(s) and is executed after the loop body is executed.
Normally there is one loop counter and a simple conditional expression however, conditions can be as complex as required and several initial and end-loop statements can be separated by commas.
The foreach Loop
This type of loop is provided specially for looping through the values of an array and is covered in the section on arrays.
The break Statement
The break statement is used to break out of a loop early i.e. before the loop condition becomes false.
It can be used with all types of loop and is used in conjunction with a conditional expression.