Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

continue 2 and break in switch statement

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 } 
like image 621
typeof programmer Avatar asked Oct 17 '14 18:10

typeof programmer


People also ask

Can you use continue in a switch statement?

We can not use a continue with the switch statement. The break statement terminates the whole loop early. The continue statement brings the next iteration early. It stops the execution of the loop.

How do you use switch break and continue statement in a program?

The break statement is usually used with the switch statement, and it can also use it within the while loop, do-while loop, or the for-loop. The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.

What is the importance of break and continue in switch statement?

The one-token statements continue and break may be used within loops to alter control flow; continue causes the next iteration of the loop to run immediately, whereas break terminates the loop and causes execution to resume after the loop.

What are the differences between switch and break statement?

Break statement mainly used to terminate the enclosing loop such as while, do-while, for or switch statement wherever break is declared.


1 Answers

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.

like image 179
showdev Avatar answered Oct 05 '22 00:10

showdev