[Previous] [Contents] [Next]

Changing Loop Behavior

To break out of a loop early-before the loop condition becomes false, the break statement is useful.

break

break ends execution of the current for, foreach, while, do-while or switch structure. It accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

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.

continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

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]