break & continue
On this page
break
break exits the loop immediately. It is commonly used when you found what you need and there is no reason to keep iterating.
<?php
$numbers = [2, 4, 7, 10];
$foundOdd = null;
foreach ($numbers as $n) {
if ($n % 2 === 1) {
$foundOdd = $n;
break;
}
}
var_dump($foundOdd); // 7
continue
continue skips the current iteration and moves to the next. It is useful for filtering.
<?php
$items = ['ok', '', 'ok2', ' '];
foreach ($items as $item) {
if (trim($item) === '') {
continue;
}
echo $item . PHP_EOL;
}
break with Levels (Nested Loops)
In nested loops, you can break out of multiple levels by passing a number. Use this carefully—sometimes it is clearer to refactor into a function and return early.
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
$target = 5;
$pos = null;
for ($r = 0; $r < count($matrix); $r++) {
for ($c = 0; $c < count($matrix[$r]); $c++) {
if ($matrix[$r][$c] === $target) {
$pos = [$r, $c];
break 2; // exit both loops
}
}
}
var_dump($pos); // [1, 1]
Production Tip
Use continue for quick input filtering and guard-style logic. Use break when you can stop early for performance and clarity.