PHP break & continue
In this page:
The break Statement
break exits the loop it's inside immediately, skipping any remaining iterations entirely and jumping straight to the first line of code after the loop — useful the moment you've found what you were searching for and don't need to keep checking further elements.
Example: The break Statement
<?php
$numbers = [1, 5, 3, 8, 2];
foreach ($numbers as $n) {
if ($n == 8) {
break;
}
echo $n . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
The continue Statement
continue skips only the rest of the *current* iteration and jumps straight to the loop's next pass, without exiting the loop altogether the way break does — the right choice when you want to ignore one specific case but keep processing everything after it.
Example: The continue Statement
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
break with Multi-level Loops
break accepts an optional integer argument specifying how many nested loop levels to exit at once — break 2; from inside a doubly-nested loop exits both loops in one statement, instead of only escaping the innermost one.
Example: break with Multi-level Loops
<?php
for ($i = 1; $i <= 2; $i++) {
for ($j = 1; $j <= 2; $j++) {
if ($j == 2) {
break 2;
}
echo "$i,$j\n";
}
}
?>
Login to try C/C++/Java/PHP code in the editor
continue with Multi-level Loops
continue accepts the same kind of numeric argument as break does, letting you skip straight to the next iteration of an *outer* loop from deep inside a nested one, rather than only advancing the innermost loop's own iteration.
Example: continue with Multi-level Loops
<?php
for ($i = 1; $i <= 2; $i++) {
for ($j = 1; $j <= 2; $j++) {
if ($j == 1) {
continue 2;
}
echo "$i,$j\n";
}
}
?>
Login to try C/C++/Java/PHP code in the editor
break in switch Blocks
PHP treats switch as a loop-like structure for the purposes of break, which is exactly why every case needs its own break — without one, execution keeps falling through into the next case's code instead of exiting the switch block.
Example: break in switch Blocks
<?php
$day = "Mon";
switch ($day) {
case "Mon":
echo "Monday";
break;
case "Tue":
echo "Tuesday";
break;
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: