-2

请帮忙。

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 没有任何以下代码并且案例 4 是带有 echo 语句的案例,它怎么会输出“i 小于 5”?我很困惑,谁能给我解释一下。提前致谢。

4

2 回答 2

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>");

它将继续携带链,直到调用中断。

于 2016-07-06T12:12:00.600 回答
1

switch就是应该如何运作的。为了停止陷入下一个案例,您必须使用break关键字。我知道的每一种语言都是一样的,包括 JavaScript、PHP 和 Python。

作为参考,请查看PHP 手册

于 2016-07-06T11:49:26.260 回答