PHP - switch case 中 break 和 continue 的区别

PHP - Difference between break and continue in switch case

两者有什么区别

switch (variable) {
        case 'value':
        # code...
        break;

        case 'value':
        # code...
        break;
}

还有这个

switch (variable) {
        case 'value':
        # code...
        continue;

        case 'value':
        # code...
        continue;
}

结果真的不同还是一样?

在PHP中,以上两个代码的工作方式相同。这里的 breakcontinue 语句阻止控制转到下一个 case。那就是 continue 的行为就像这里的 break 一样。 switch 也只执行一次。这不是一个循环。因此 continue 与此处无关。

注意:如果有循环包围这个switch语句那么结果会不同。

这是 PHP 的特例,因为如 official documentation 所述:

Note: In PHP the switch statement is considered a looping structure for the purposes of continue. continue behaves like break (when no arguments are passed). If a switch is inside a loop, continue 2 will continue with the next iteration of the outer loop.

所以从本质上讲,这意味着您的两个示例之间没有实际区别。但是为了清楚起见,我认为最好使用 break 因为这是其他语言的标准。另请注意,如果开关在循环(或更多)内,则可以使用 continue 2(或 3、4...)前进到循环的下一次迭代。

这是一个简单的示例代码,其中包含上述两种情况

<?php
    $variable = 20;
    echo "Normal<br/>";
    switch ($variable) {
        case '20':
            echo "twenty";
        break;
        case '21':
            echo "twenty one";
        break;
    }

    echo "<br/><br/>With Continue<br/>";
    switch ($variable) {
        case '20':
            echo "twenty";
        continue;
        case '21':
            echo "twenty one";
        continue;
    }
?>

当我执行上面的代码时,我得到了以下输出

Normal
twenty

With Continue
twenty

怎么办?

break 语句的工作

Break statement导致代码执行跳出块,执行下一条语句,因为switch语句只会执行一个case语句,退出switch块,不执行其他case块。

Continue 语句的工作

Continue statement 在循环的情况下将导致循环停止执行循环的当前迭代并转到循环的下一次迭代(如果存在)但在 switch 语句的情况下它被视为循环语句但没有下一次迭代导致退出 switch 语句。

我们也可以像这样有一个没有 break 语句的 switch 语句

<?php
    $variable = 20;
    echo "Normal";
    switch ($variable) {
        case '19':
            echo "<br/>Nineteen";
        case '20':
            echo "<br/>twenty";
        case '21':
            echo "<br/>twenty one";
        case '23':
            echo "<br/>twenty three";
    }
?>

以上代码的输出将是

Normal
twenty
twenty one
twenty three

即在找到第一个匹配的 case 之后执行所有 case 语句。