24

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?

hjpotter92
  • 71,576
  • 32
  • 131
  • 164
funguy
  • 1,914
  • 7
  • 24
  • 38
  • 23
    Did you notice the comments in the code example you just gave? I think they do a fairly good job explaining it. – BoltClock Sep 23 '12 at 13:27
  • So what it would be in this example if we would have only 'break', not 'break 2'? – funguy Sep 23 '12 at 13:37
  • It would stay within the `while` loop. And given the condition, it would output *Chocolate is in stock!* forever :) – Jason McCreary Sep 23 '12 at 13:39
  • 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. – Manolis Agkopian Sep 23 '12 at 13:41

1 Answers1

28

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;
      }
    }
  }
}
Jason McCreary
  • 66,624
  • 20
  • 123
  • 167
  • 3
    So in this case, it breaks the switch and the while – Basic Sep 23 '12 at 13:28
  • Just beware that it should be like ***break ;*** As of PHP 5.4.0 You may not pass in variables (e.g., $num = 2; break $num;) as the numerical argument. – Tarik Aug 27 '17 at 10:43