53

I am new to PHP and saw the code below online. It has continue 2 and break together in switch/case statement. What does it mean?

foreach ( $elements as &$element ) {

    switch ($element['type']) {
        case a :
            if (condition1)
                continue 2; 
            break;

        case b :
            if (condition2)
                continue 2;
            break;
    }

    // remaining code here, inside loop but outside switch statement
}

3 Answers 3

78

The continue 2 skips directly to the next iteration of the structure that is two levels back, which is the foreach. The break (equivalent to break 1) just ends the switch statement.

The behavior in the code you've shown is:

Loop through $elements. If an $element is type "a" and condition1 is met, or if it's type "b" and condition2 is met, skip to the next $element. Otherwise, perform some action before moving to the next $element.


From PHP.net:continue:

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.

From PHP.net:switch

PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement.

If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

4
  • Thanks for your kindly answer. So, you mean, if the type is "a" and condition1 is met or if the type is "b" and condition2 is met, the remaining code in loop which outside switch statement will not be executed and will jump to next iteration in the loop, right? Commented Oct 17, 2014 at 18:35
  • 2
    Yes, that's right. continue 2 skips directly to the next iteration of the foreach loop without executing any code after the switch. Here's a demonstration.
    – showdev
    Commented Oct 17, 2014 at 18:57
  • Get it. Thanks for kindly explanation. Commented Oct 17, 2014 at 19:06
  • My link above is dead. Here's a replacement
    – showdev
    Commented Jun 7, 2019 at 18:31
4

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.

Source: http://php.net/manual/en/control-structures.continue.php

2

continue and break are similar in that the will stop something from happening.

in case of continue, it will stop anything after the braces but won't stop the loop. The switch statement just gets out of this statement and goes on to the next statement.

In case of break it will stop the entire loop from continuing, end the loop there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.