“break 2”是什么意思?

时间:2012-09-23 13:26:33

标签: php break control-structure

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

 <?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'语句是否有更多可用选项?

1 个答案:

答案 0 :(得分:21)

来自PHP docs on break

  

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

正如评论中所指出的那样,开关和时会突然出现。

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

foreach (...) {
  foreach (..) {
    foreach (...) {
      if ($condition) {
        break 3;
      }
    }
  }
}