请帮忙。
for($i=0; $i<12; $i++ ){
switch($i) {
case 0:
case 1:
case 2:
case 3:
case 4:
echo ("i is less than 5 <br>");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
echo ("i is less than 10 <br>");
break;
default:
echo ("i is 10 or more <br>");
}
}
这是我在Java书中得到的示例代码,我将上面的代码翻译成了PHP。
以下代码的输出:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
我的问题是,如果0到案例3输出“i小于5”,即使它没有任何下面的代码,情况4是带有echo语句的那个,怎么办?我很困惑,有人可以向我解释一下。提前谢谢。
答案 0 :(得分:1)
switch
应该如何运作。为了不再涉及下一个案例,您必须使用break
关键字。我所知道的每种语言都是一样的,包括JavaScript,PHP和Python。
供参考,请查看PHP manual。
答案 1 :(得分:1)
想象你的开关就像这样
switch($i) {
case 0:
case 1:
case 2:
case 3:
case 4:
echo ("i is less than 5 <br>");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
echo ("i is less than 10 <br>");
break;
default:
echo ("i is 10 or more <br>");
它将一直沿着链子传递,直到打破休息。