continue

(PHP 4, PHP 5, PHP 7)
Examples:

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

Note: In PHP the switch statement is considered a looping structure for the purposes of continue. continue behaves like break (when no arguments are passed). If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop.

continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.

<?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip even members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "Middle<br />\n";
        while (1) {
            echo "Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>

One can expect the result to be:

Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

0
1
3
4

but, in PHP versions below 5.4.0, this script will output:

2

because the entire continue print "$i\n"; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

Note:

As of PHP 5.4.0, the above example will raise an E_COMPILE_ERROR error.

doc_php
2016-02-24 15:53:01
Comments
Leave a Comment

Please login to continue.