Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "break 2"?

I always used and seen examples with just "break". What is the meaning of this:

 <?php      while ($flavor = "chocolate") {        switch ($flavor) {          case "strawberry";              echo "Strawberry is stock!";              break 2;    // Exits the switch and the while          case "vanilla";              echo "Vanilla is in stock!";              break 2;   // Exits the switch and the while          case "chocolate";              echo "Chocolate is in stock!";              break 2;    // Exits the switch and the while          default;                  echo "Sorry $flavor is not in stock";              break 2;    // Exits the switch and the while        }      }      ?> 

Are there more available options available with the 'break' statement?

like image 440
funguy Avatar asked Sep 23 '12 13:09

funguy


People also ask

How to use break in PHP?

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only. The break keyword immediately ends the execution of the loop or switch structure.

Can I break foreach in PHP?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.

What is use of break and continue statements in PHP scripts?

The break statement terminates the whole iteration of a loop whereas continue skips the current iteration. The break statement terminates the whole loop early whereas the continue brings the next iteration early.


1 Answers

From the PHP docs on break:

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

As noted in the comments it breaks out of the switch and while.

The following example would break out of all foreach loops:

foreach (...) {   foreach (..) {     foreach (...) {       if ($condition) {         break 3;       }     }   } } 
like image 59
Jason McCreary Avatar answered Sep 19 '22 07:09

Jason McCreary