TExcelTAD
Home › PHP › PHP Break & Continue

PHP Break & Continue

Sometimes a loop shouldn't simply run from start to finish. You may want to stop early once you have found what you were looking for, or skip an item that doesn't need processing. PHP provides two statements for that: break and continue. Both work in for, foreach, while and do...while loops (and break also in switch).

Statement Effect
break leave the loop immediately; continue after it
continue skip the rest of this pass; start the next one
break 2 / continue 2 the same, but for the enclosing loop two levels up

break: stop the loop

A typical use is a search: once the item is found, there is no reason to keep looking.

php · try it yourself
<?php
$inventory = ["hammer", "saw", "drill", "wrench", "pliers"];
$wanted = "drill";

foreach ($inventory as $position => $tool) {
    echo "Checking $tool...\n";
    if ($tool === $wanted) {
        echo "Found $wanted at position $position\n";
        break;
    }
}
echo "Search finished\n";
Checking hammer...
Checking saw...
Checking drill...
Found drill at position 2
Search finished

wrench and pliers were never checked. break is also handy to exit a deliberately endless while (true) loop when a condition is met inside the body:

php · try it yourself
<?php
$total = 0;
$n = 0;

while (true) {
    $n++;
    $total += $n;
    if ($total > 50) {
        break;
    }
}

echo "Adding 1 + 2 + ... + $n gives $total, the first sum above 50\n";
Adding 1 + 2 + ... + 10 gives 55, the first sum above 50

continue: skip one pass

continue jumps straight to the next iteration. Use it to filter out items you don't want to handle, which keeps the main logic un-indented:

php · try it yourself
<?php
$readings = [21.5, null, 23.0, -999, 22.4, null, 24.1];
$valid = [];

foreach ($readings as $r) {
    if ($r === null) {
        continue;           // sensor was offline
    }
    if ($r < -100) {
        continue;           // obviously broken value
    }
    $valid[] = $r;
}

echo "Valid readings: ", implode(", ", $valid), "\n";
printf("Average: %.2f\n", array_sum($valid) / count($valid));
Valid readings: 21.5, 23, 22.4, 24.1
Average: 22.75

In a for loop, continue still runs the step expression ($i++), so the loop advances normally. In a while loop, make sure the variable is updated before the continue, or you can end up in an endless loop.

php · try it yourself
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i % 3 !== 0) {
        continue;
    }
    echo "$i is divisible by 3\n";
}
3 is divisible by 3
6 is divisible by 3
9 is divisible by 3

Leaving nested loops

Plain break only exits the innermost loop. Give it a number to break out of several levels at once. The same works for continue:

php · try it yourself
<?php
$grid = [
    [3, 8, 1],
    [9, 4, 7],
    [5, 2, 6],
];
$target = 7;

foreach ($grid as $row => $cells) {
    foreach ($cells as $col => $value) {
        if ($value === $target) {
            echo "Found $target at row $row, column $col\n";
            break 2;        // leave both loops
        }
    }
}

// continue 2: skip the rest of the current row
foreach ($grid as $row => $cells) {
    foreach ($cells as $value) {
        if ($value > 8) {
            echo "Row $row contains a value above 8, skipping it\n";
            continue 2;
        }
    }
    echo "Row $row is fine\n";
}
Found 7 at row 1, column 2
Row 0 is fine
Row 1 contains a value above 8, skipping it
Row 2 is fine

Note: break inside a switch that sits inside a loop only leaves the switch. To leave the loop as well, use break 2. Similarly, continue inside a switch acts like continue for the surrounding loop, but PHP recommends writing continue 2 there to make the intent explicit.

Tip: If you find yourself needing break 3, consider moving the nested loops into a function and using return — it is often much easier to read.

Test yourself

What does continue do inside a loop?

  1. Exits the loop
  2. Restarts the loop from the first element
  3. Skips the rest of the current pass and moves to the next one
  4. Pauses the program

What is printed by for ($i = 0; $i < 5; $i++) { if ($i == 3) break; echo $i; }?

  1. 012
  2. 0123
  3. 01234
  4. 0124

How do you exit two nested loops at once?

  1. break; break;
  2. exit 2;
  3. break 2;
  4. return loop;