“break 2” 是什么意思?(涉及IT技术)

31

我经常使用并看到只有"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'语句还有其他可用选项吗?


28
你有没有注意到你刚刚给出的代码例子中的注释?我认为它们很好地解释了代码的含义。 - BoltClock
如果在这个例子中我们只有'break'而没有'break 2',那么会怎样? - funguy
1
它将保持在while循环内。鉴于条件,它将永远输出“巧克力有库存!” :) - Jason McCreary
break 可以用于两个方面。
  1. 结束 switch 中的 case 语句,并且不继续执行其他语句。
  2. 立即终止循环。可选参数定义要终止的语句级别,默认值为 1。
- Manolis Agkopian
1个回答

39

3
在这种情况下,它会打断开关和while循环。 - Basic
请注意,它应该是像 break <integer>; 这样的形式。从 PHP 5.4.0 开始,您不能将变量(例如,$num = 2; break $num;) 作为数值参数传递。 - Tarik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接