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.
foreach ($items as $item) { if ($item === null) { continue; } if ($item === "end") { break; } echo $item; }
Try it
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.
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
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
breakin aswitchends the switch, not the surrounding loop. Usebreak 2to leave both. Seeswitch.continuein aswitchbehaves likebreakfor the switch itself, so PHP warns about it. Writecontinue 2to continue the enclosing loop.- Where
continuegoes. Infor, the step expression still runs; inwhileanddo-while, control returns to the condition test. - Keep levels small.
break 3is hard to read. Extract the inner loops into a function andreturninstead. - Guard clauses.
continuenear the top of a loop body avoids deep nesting. breakis not an exit from a function. Usereturn.- Not usable with
match.matchis an expression with no fall-through.