The break Construct

The break construct immediately terminates the execution of the current loop (for, while, do-while, or foreach) or the switch statement. After executing break, control is passed to the line of code immediately following the interrupted construct.

After the break command, you can write a number that indicates how many nested constructs should be interrupted (default is 1).

Syntax

phpbreak;
phpbreak $level;

Example

Loop interruption when a condition is met:

php<?php
  for ($i = 0; $i < 5; $i++) {
    if ($i == 3) {
      break;
    }
    echo $i;
  }
?>

Code execution result:

php'012'

Example

Usage in the switch statement:

php<?php
  $value = 2;
  switch ($value) {
    case 1:
      echo 'One';
      break;
    case 2:
      echo 'Two';
      break;
    default:
      echo 'Other';
  }
?>

Code execution result:

php'Two'

Example

Interrupting nested loops with level specification:

php<?php
  for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
      if ($j == 1) {
        break 2; // Interrupts both loops
      }
      echo $i.$j;
    }
  }
?>

Code execution result:

php'00'

See Also

  • the continue construct,
    which interrupts the current iteration of a loop
  • the switch construct,
    which selects one of the code blocks to execute