如何在不停止 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
How to stop foreach cycle without stopping the rest of the PHP script?
提问by daGrevis
Having a foreach
loop, 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 return
and exit
, but it didn't work as expected, because I want to continue executing the remaining of the PHP script.
我尝试使用return
and exit
,但它没有按预期工作,因为我想继续执行剩余的 PHP 脚本。
回答by Tatu Ulmanen
回答by jolt
http://php.net/manual/en/control-structures.break.phpis the answer!
http://php.net/manual/en/control-structures.break.php就是答案!
As simple as break;
.
一样简单break;
。