How to Continue or Break an Outer Loop From a Nested One in PHP?

Quick overview of how to break out of, or skip an iteration in an outer loop in PHP

Breaking Outer Loop

In PHP, we can specify an optional numeric argument to break to specify which loop to break out of. By default this value is 1 which means the current/immediate loop. If this value is 2 for example, it would refer to the parent loop, and so on. Basically each increment in this number refers to one loop up the nesting order.

For example, to break the outer-most loop from a three-level nesting of loops, we would use break 3 in the inner-most loop like so:

while (true) {
    while (true) {
        while (true) {
            break 3;
        }

        echo 'does not reach here';
    }

    echo 'does not reach here';
}

Breaking Outer Loop From a switch Statement:

Breaking outer loops from a switch statement can be done like so:

$i = 0;

while (++$i) {
    switch ($i) {
        case 2:
            echo 'Breaking switch only;';
            break 1;
        case 5:
            echo 'Breaking switch + while;';
            break 2;
        default:
            echo "{$i};";
            break;
    }
}

// output: '1;Breaking switch only;3;4;Breaking switch + while;'

Skipping Outer Loop Iteration

To skip to the next iteration of the outer loop, we can make use of continue. Similar to break, continue accepts an optional numeric argument as well which can be used to specify which loop to skip to the next iteration. By default this value is 1 which means the current/immediate loop. If this value was 2 it would mean continue/skip to the next iteration of the loop that's one level up, and so on. For example:

$i = 0;

while ($i++ < 2) {
    echo '3;';

    while (true) {
        echo '2;';

        while (true) {
            echo '1;';
            continue 3;
        }

        echo 'does not reach here';
    }

    echo 'does not reach here';
}

// output: '3;2;1;3;2;1;'

Skipping Outer Loop Iteration From a switch Statement:

If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop (that's one level up), and so on.

Using continue without an argument inside a switch statement behaves like break (and raises a warning). Generally, you should avoid using continue inside switch (and use break instead) unless it's to continue/skip to then next iteration of an outer loop.

For example:

$i = 0;

while (++$i) {
    switch ($i) {
        case 2:
        case 4:
            echo 'skip;';
            continue 2;
        case 5:
            echo 'Breaking switch + while;';
            break 2;
        default:
            break;
    }

    echo "{$i};";
}

// output: '1;skip;3;skip;Breaking switch + while;'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.