切换太频繁触发

Switch too often triggered

我无法理解这个问题。可能有一个简单的解决方案并且问题已经解决,但我找不到答案。

<?php
    $string = '';
    $array = array(1, 2, 3);
    foreach($array as $number) {
        switch($number) {
            case '1':
                $string .= 'I ';
            case '2':
                $string .= 'love ';
            case '3':
                $string .= 'you';
        }
    }
    echo $string;
    ?>

你可能已经猜到了,生成的句子应该是:我爱你

但这是实际输出:我爱你爱你你

当开关只触发三次时,这怎么可能。 同时我知道这个问题可以通过 >break;< 在每个案例之后解决。但我仍然不明白为什么这是必要的。 如果有人能向我解释 PHP 在做什么,我会很高兴。 情人节快乐!

当 case 1 被匹配时它也会执行 case 23 除非有中断。

所以每次循环都会执行匹配的 case 和后面的所有内容。

First time: case 1, 2, 3

Second time: case 2, 3

Third time: case 3

作为参考,这里是 the PHP documentation on switch 的摘录,它比我可能会更好地解释它。 :)

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
    case 0:
        echo "i equals 0";
    case 1:
        echo "i equals 1";
    case 2:
        echo "i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

当您不指定 break 时,代码执行将跳转到下一个案例。

例如,一份满分 10 分的试卷可以这样评分:

switch ($score)
{
    case 10:
        // A+ when score is 10
        echo 'A+';
        break;
    case 9:
    case 8:
        // A when score is 8 or 9
        echo 'A';
        break;
    case 7:
    case 6:
        // B when score is 7 or 6
        echo 'B';
        break;
    case 5:
    case 4:
    case 3:
        // C when score between 3 and 5
        echo 'C';
        break;
    default:
        // Failed if score is less than 3
        echo 'Failed';
}