[Previous] [Contents] [Next]

Loops

Loops in PHP have the same syntax as other high-level programming languages.

Loops add control to scripts so that statements can be repeatedly executed as long as a conditional expression remains true. There are four loop statements in PHP: while, do...while, for, and foreach. The first three are general-purpose loop constructs, and foreach is used exclusively with arrays.

while

The while loop is the simplest looping structure but sometimes the least compact to use. The while loop repeats one or more statements-the loop body-as long as a condition remains true. The condition is checked first, then the loop body is executed. So, the loop never executes if the condition isn't initially true. Just as in the if statement, more than one statement can be placed in braces to form the loop body.

The following fragment illustrates the while statement by printing out the integers from 1 to 10 separated by a space character:

$counter = 1;
while ($counter < 11)
{
  echo $counter;
  echo " ";
  // Add one to $counter
  $counter++;
}

do...while

The difference between while and do...while is the point at which the condition is checked. In do...while, the condition is checked after the loop body is executed. As long as the condition remains true, the loop body is repeated.

You can emulate the functionality of the while example as follows:

$counter = 1;
do
{
  echo $counter;
  echo " ";
  $counter++;
} while ($counter < 11);

The contrast between while and do...while can be seen in the following example:

$counter = 100;
do
{
  echo $counter;
  echo " ";
  $counter++;
} while ($counter < 11);

This example outputs 100, because the body of the loop is executed once before the condition is evaluated as false.

The do...while loop is the least-frequently used loop construct, probably because executing a loop body once when a condition is false is an unusual requirement.

[Previous] [Contents] [Next]