daG*_*vis 12 php foreach loops
有一个foreach循环,如果某个条件变得有效,是否可以停止它?
<?php
foreach ($foo as $bar) {
if (2+2 === 4) {
// Do something and stop the cycle
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我试图使用return和exit,但它没有按预期工作,因为我想继续执行剩余的PHP脚本.
Tat*_*nen 46
用途break:
foreach($foo as $bar) {
if(2 + 2 === 4) {
break;
}
}
Run Code Online (Sandbox Code Playgroud)
Break将跳出foreach循环并继续正常执行.如果您只想跳过一次迭代,则可以使用continue.