[Previous] [Contents] [Next]


Changing Loop Behavior


To break out of a loop early-before the loop condition becomes false-the break statement is useful. This example illustrates the idea:

for($x=0; $x<100; $x++)
{
  if ($x > $y)
    break;
  echo $x;
}

If $x reaches 100, the loop terminates normally. However, if $x is (or becomes) greater than $y, the loop is terminated early, and program execution continues after the loop body. The break statement can be used with all loop types.

To start again from the top of the loop without completing all the statements in the loop body, use the continue statement. Consider this example:

$x = 1;

while($x<100)
{
  echo $x;
  $x++;
  if ($x > $y)
    continue;
  echo $y;
}

The example prints and increments $x each time the loop body is executed. If $x is greater than $y, the loop is begun again from the top; otherwise, $y is printed, and the loop begins again normally. Like the break statement, continue can be used with any loop type.


[Previous] [Contents] [Next]