PHP Break & Continue
break exits the loop. continue skips to the next iteration. Both take an optional level for nested loops.
break
PHP
foreach ($users as $u) {
if ($u->isBanned()) {
echo 'Stopping: banned user found.';
break;
}
process($u);
}
continue
PHP
foreach ($numbers as $n) {
if ($n % 2 === 0) continue; // skip evens
echo $n, PHP_EOL;
}
Levels — break out of nested loops
PHP
foreach ($rows as $row) {
foreach ($row as $cell) {
if ($cell === 'STOP') {
break 2; // exit BOTH loops
}
}
}
continue 2 works the same — skip the rest of the inner body and continue the outer loop.
continue in switch
Inside a switch, continue by itself acts like break — to actually continue the surrounding loop, use continue 2:
PHP
foreach ($items as $i) {
switch ($i->type) {
case 'skip':
continue 2; // skip to next foreach iteration
default:
process($i);
}
}
Tip: A loop that needs
break 3 is usually a sign to extract a function and return instead. Way easier to read.Example
Example
<?php
for ($i = 0; $i < 10; $i++) {
if ($i === 3) continue;
if ($i === 7) break;
echo $i, PHP_EOL;
}
Try it Yourself »
Exercise
Exit two nested loops at once with…
break
;
A single digit.
Discussion
Loading…