Вопрос

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?

Это было полезно?

Решение

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;
      }
    }
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top