break and continue

Control loop flow by exiting early or skipping an iteration.

Syntaxbreak; continue;

Two keywords let you change how a loop runs:

  • break — immediately stops the loop entirely.
  • continue — skips the rest of the current iteration and moves to the next.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Exit a search loop as soon as the target item is found to avoid unnecessary iterations.
  • Skip logging entries that match 'DEBUG' level when only warnings and errors are needed.
  • Break out of nested loops with break 2 when a match is found in a 2-D grid search.

More examples

break exits the loop early

break immediately exits the enclosing loop, avoiding wasted iterations once the target is located.

Example · php
<?php
$items = [3, 7, 12, 5, 9];
$found = null;

foreach ($items as $item) {
    if ($item === 12) {
        $found = $item;
        break;
    }
}

echo $found !== null ? "Found: $found" : 'Not found';

continue skips an iteration

continue skips the rest of the current iteration and moves to the next, filtering items without nesting.

Example · php
<?php
$logLines = ['INFO: start', 'DEBUG: x=1', 'ERROR: failed', 'DEBUG: y=2'];

foreach ($logLines as $line) {
    if (str_starts_with($line, 'DEBUG')) {
        continue; // skip debug lines
    }
    echo $line . "\n";
}

break 2 in nested loops

break 2 exits two levels of nesting at once, returning control past the outer loop without a flag variable.

Example · php
<?php
$grid = [
    ['a', 'b', 'c'],
    ['d', 'TARGET', 'f'],
    ['g', 'h', 'i'],
];

foreach ($grid as $row => $cols) {
    foreach ($cols as $col => $cell) {
        if ($cell === 'TARGET') {
            echo "Found at [$row][$col]";
            break 2; // exit both loops
        }
    }
}

Discussion

  • Be the first to comment on this lesson.
break and continue — PHP | SoundsCode