What is the meaning of "break 2"?
Asked Answered
E

1

33

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?

Encomium answered 23/9, 2012 at 13:26 Comment(4)
Did you notice the comments in the code example you just gave? I think they do a fairly good job explaining it.Instrumentalism
So what it would be in this example if we would have only 'break', not 'break 2'?Encomium
It would stay within the while loop. And given the condition, it would output Chocolate is in stock! forever :)Prejudicial
The break can be used for 2 things. 1. To end the case statements in a switch and don't continue execution with the other. 2. To terminate a loop immediately. The optional parameter defines the level of the statement to be terminated. And it's default value is 1.Almond
P
42

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;
      }
    }
  }
}
Prejudicial answered 23/9, 2012 at 13:27 Comment(2)
So in this case, it breaks the switch and the whileUdometer
Just beware that it should be like break <integer>; As of PHP 5.4.0 You may not pass in variables (e.g., $num = 2; break $num;) as the numerical argument.Bontebok

© 2022 - 2024 — McMap. All rights reserved.