typeof programmer typeof programmer - 6 months ago 55
PHP Question

continue 2 and break in switch statement

I am new to PHP and saw the code below online. It has

continue 2
together in
statement. What does it mean?

foreach ( $elements as &$element ) {

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

case b :
if (condition2)
continue 2;

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


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

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

PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

Explanation: The continue 2 jumps to the next iteration of the loop at 2 levels back, which is the foreach. The break (equivalent to break 1) ends the current loop, which is the switch.

In english: For each $element, if the type is "a" and condition1 is met or if the type is "b" and condition2 is met, continue to the next $element and ignore the rest of the switch options. Otherwise, continue to the next switch option or, if this is the last switch option, execute any code after the switch.

Here's a demonstration.