在 PHP 中,break 和 continue 之间的区别?

php
2022-08-30 06:29:55

在 PHP 中,breakcontinue 有什么区别?


答案 1

break完全结束循环,只需快捷方式当前迭代并转到下一个迭代。continue

while ($foo) {   <--------------------┐
    continue;    --- goes back here --┘
    break;       ----- jumps here ----┐
}                                     |
                 <--------------------┘

这将像这样使用:

while ($droid = searchDroids()) {
    if ($droid != $theDroidYoureLookingFor) {
        continue; // ..the search with the next droid
    }

    $foundDroidYoureLookingFor = true;
    break; // ..off the search
}

答案 2

break 退出您所处的循环,继续从循环的下一个循环开始。

例:

$i = 10;
while (--$i)
{
    if ($i == 8)
    {
        continue;
    }
    if ($i == 5)
    {
        break;
    }
    echo $i . "\n";
}

将输出:

9
7
6

推荐