← Back to PHP Course | Chapter 4: Control Flow | Lesson 14 of 14

PHP break & continue

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
<?php
$numbers = [1, 5, 3, 8, 2];
foreach ($numbers as $n) {
    if ($n == 8) {
        break;
    }
    echo $n . "\n";
}
?>

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
<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) {
        continue;
    }
    echo $i . "\n";
}
?>

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
<?php
for ($i = 1; $i <= 2; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        if ($j == 2) {
            break 2;
        }
        echo "$i,$j\n";
    }
}
?>

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
<?php
for ($i = 1; $i <= 2; $i++) {
    for ($j = 1; $j <= 2; $j++) {
        if ($j == 1) {
            continue 2;
        }
        echo "$i,$j\n";
    }
}
?>

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
<?php
$day = "Mon";
switch ($day) {
    case "Mon":
        echo "Monday";
        break;
    case "Tue":
        echo "Tuesday";
        break;
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.