Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

PHP break and continue

Reference for PHP break and continue: leave a loop or skip to the next iteration, numeric levels for nested loops, and behavior inside switch.

break ends the innermost loop (or switch) immediately. continue skips the rest of the current iteration and moves on to the next one. Both accept an optional positive integer that says how many nested structures to affect, so you can leave an outer loop from inside an inner one.

They only work inside for, foreach, while, do-while and switch. Using them anywhere else is a compile-time error.

PHP
foreach ($items as $item) {
    if ($item === null) { continue; }
    if ($item === "end") { break; }
    echo $item;
}

Try it

PHP Skipping and stopping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Nested loops with levels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
break;
break $levels;
continue;
continue $levels;
Name Description
$levels Optional literal positive integer (default 1): how many enclosing loop or switch structures to leave or continue.

Return value: none.

Errors: a fatal error at compile time if $levels is zero, negative, not a literal integer (since PHP 5.4), or larger than the number of enclosing structures; "break" or "continue" outside a loop or switch is also a fatal error.

Usage notes

  • break in a switch ends the switch, not the surrounding loop. Use break 2 to leave both. See switch.
  • continue in a switch behaves like break for the switch itself, so PHP warns about it. Write continue 2 to continue the enclosing loop.
  • Where continue goes. In for, the step expression still runs; in while and do-while, control returns to the condition test.
  • Keep levels small. break 3 is hard to read. Extract the inner loops into a function and return instead.
  • Guard clauses. continue near the top of a loop body avoids deep nesting.
  • break is not an exit from a function. Use return.
  • Not usable with match. match is an expression with no fall-through.