PHP中断和继续的区别?

时间:2010-12-06 09:10:12

标签: php

PHP中breakcontinue之间有什么区别?

10 个答案:

答案 0 :(得分:434)

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
}

答案 1 :(得分:37)

break退出你所在的循环,然后立即开始循环的下一个循环。

示例:

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

将输出:

9
7
6

答案 2 :(得分:13)

BREAK:

  

break结束当前的执行   for,foreach,while,do-while或   开关结构。

CONTINUE:

  

continue在循环中使用   结构跳过剩下的   当前循环迭代并继续   在条件评估中执行   然后是下一个的开始   迭代。

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

另外,请参阅here了解详细信息Break off Continue以及一些示例

答案 3 :(得分:11)

记录:

  

请注意,在PHP中,开关语句被视为循环   结构用于继续

答案 4 :(得分:4)

Break结束当前的循环/控制结构并跳到它的末尾,无论循环多少次都会重复。

继续跳到循环的下一次迭代的开始。

答案 5 :(得分:4)

在循环结构中使用

'continue'跳过当前循环迭代的其余部分,并在条件评估和下一次迭代开始时继续执行。

'break'结束当前for,foreach,while,do-while或switch结构的执行。

break接受一个可选的数字参数,该参数告诉它有多少嵌套的封闭结构被打破。

查看以下链接:

http://www.php.net/manual/en/control-structures.break.php

http://www.php.net/manual/en/control-structures.continue.php

希望有所帮助......

答案 6 :(得分:4)

break用于从循环语句中退出,但继续只是在特定条件下停止脚本然后继续循环语句直到结束..

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

希望它可以帮助你;

答案 7 :(得分:2)

break将停止当前循环(或传递一个整数来告诉它要断开多少循环)。

continue将停止当前迭代并启动下一个迭代。

答案 8 :(得分:2)

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

答案 9 :(得分:0)

我在这里写的不一样。只是PHP手册中的变更日志记录。


  

更改日志以继续

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.
  

休息的变更日志

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.