如何在不停止 PHP 脚本的其余部分的情况下停止 foreach 循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5218998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:40:23  来源:igfitidea点击:

How to stop foreach cycle without stopping the rest of the PHP script?

phploopsforeach

提问by daGrevis

Having a foreachloop, is it possible to stop it if a certain condition becomes valid?

有一个foreach循环,如果某个条件有效,是否可以停止它?

Example:

例子:

<?php
foreach ($foo as $bar) {

  if (2+2 === 4) {
    // Do something and stop the cycle
  }

}
?>

I tried to use returnand exit, but it didn't work as expected, because I want to continue executing the remaining of the PHP script.

我尝试使用returnand exit,但它没有按预期工作,因为我想继续执行剩余的 PHP 脚本。

回答by Tatu Ulmanen

Use break:

使用break

foreach($foo as $bar) {    
    if(2 + 2 === 4) {
        break;    
    }    
}

Break will jump out of the foreachloop and continue execution normally. If you want to skip just one iteration, you can use continue.

Break 会跳出foreach循环,继续正常执行。如果只想跳过一次迭代,可以使用continue.

回答by jolt