28

我总是使用和看到只有“break”的例子。这是什么意思:

 <?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 
      } 
    } 
    ?>

'break' 语句是否有更多可用选项?

4

1 回答 1

33

来自PHP 文档break

break 接受一个可选的数字参数,告诉它有多少嵌套的封闭结构要被打破。

如评论中所述,它从switch 和 while中脱颖而出。

以下示例将打破所有foreach循环:

foreach (...) {
  foreach (..) {
    foreach (...) {
      if ($condition) {
        break 3;
      }
    }
  }
}
于 2012-09-23T13:27:48.567 回答