typeof programmer typeof programmer - 4 months ago 9
PHP Question

PHP what if continue 2 and break both in switch case statement

I am new to PHP. I saw the below code online, it comes with 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 in loop which outside switch statement
}

Answer

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.