Login | Contact Us | Site Map | Resources

PHP Conditions & Loops

Home > PHP Tutorial > Breaking Out of Loops

Breaking Out of Loops

There will be time when you want to break out of, or end a loop before it is complete, usually when a certain condition is met. The break statement makes this possible.

<?php
  $number = 75;
  for ($count=1; $count<=10; $count++) {
    if ($number>300) { break; }
    echo $number . "<br>";
    $number += 75;
  }
?>

By adding a single line of code to the for loop that we have already examined, we can see the break statement in action. If the value of the number variable is greater than 300, the break statement is executed. When the break statement is executed, the loop is abruptly broken out of, so that the remaining code and remaining/unfinished loops are all ignored.

The result will be:

75
150
225
300

If multiple loops are nested, the break statement accepts a numerical value to indicate how many loops to break out of. The statement "break 1;" is the same as saying "break;", so to break out of two loop at once the correct statement is "break 2;" etc.

<?php
  $a = 0;
  $b = 7;
  while ($a<50) {
    for ($c=0; $c<3; $c++) {
      $b = $b + $b - 2;
      echo $b . "<br>";
      if ($b>500) { break 2; }
    $a++;
    }
  }
?>

So in this example we see a while loop that contains a for loop that contains a condition saying "if the $b variable value is greater than 500, break out of 2 loops". Can you figure out what else this block of code is saying, and what the result will be?

I'll give you a hint:

12
22
42
82
162
322
642