PHP中break和continue的区别是什么?

187
10个回答

553

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
}

57
这些功能被滥用会导致这种情况发生:http://www.flickr.com/photos/24973901@N04/2762458387/ - designosis
7
喜欢这个答案!它让我想起了 WP.org 对 Yoda Conditions 的建议:http://make.wordpress.org/core/handbook/coding-standards/php/#yoda-conditions - Bob Gregor
4
虽然距离这个回答已经过去了7年,但仍值得提及。从v4开始,在php文档中,switch语句中的breakcontinue作用相同,都会退出switch语句。如果要退出外部循环(例如for循环),可以使用continue 2 - Amin.Qarabaqi
@BobGregor 目前该部分可以在 https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions 找到。 - Douwe de Haan

52

使用 break 语句可以退出当前循环,而 continue 语句则会立即开始下一次循环。

例如:

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

会输出:

9
7
6

19

BREAK:

break用于结束当前的for、foreach、while、do-while或switch结构。

CONTINUE:

continue用于在循环结构中跳过当前剩余的循环迭代,继续执行条件判断和下一次迭代的开始。

因此,根据需要,您可以重置代码中当前正在执行的位置到当前嵌套级别的不同层次。

另外,请参见这里,其中详细介绍了Break vs Continue,并提供了许多示例。


16

声明如下:

请注意,在PHP中,switch语句被视为循环结构,因此适用于continue


我刚被这个“特性”咬了一口。如何基于在switch case中发现的事物继续while循环? - MattBianco
1
@MattBianco,在这些情况下你可以使用 continue 2 - flaviovs

7

break语句用于跳出循环,而continue语句则是在满足特定条件时停止当前脚本执行,并继续循环直到结束。

for($i=0; $i<10; $i++){
    if($i == 5){
        echo "It reach five<br>";
        continue;
    }
    echo $i . "<br>";
}

echo "<hr>";

for($i=0; $i<10; $i++){
    if($i == 5){
         echo "It reach end<br>";
         break;
    }
    echo $i . "<br>";
}

希望这可以帮助您;


5

4

break会停止当前循环(或传递一个整数告诉它要从多少个循环中退出)。

continue会停止当前迭代并开始下一个迭代。


4

Break语句可以结束当前的循环/控制结构,并跳到它的结尾,无论这个循环本来应该重复多少次。

而Continue语句则是跳过当前循环的剩余部分,立即进入下一次迭代。


2

break会退出循环,而continue会立即开始循环的下一个周期。


2

我这里没有写任何东西。这只是PHP手册中的变更日志。


continue的变更日志

Version Description

7.0.0 - continue outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.

5.4.0   continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.

5.4.0   Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.
break的更新日志
Version Description

7.0.0   break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.

5.4.0   break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.

5.4.0   Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接