[Previous] [Contents] [Next]


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]