Having a foreach
loop, is it possible to stop it if a certain condition becomes valid?
<?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.
Use break
:
foreach($foo as $bar) {
if(2 + 2 === 4) {
break;
}
}
Break will jump out of the foreach
loop and continue execution normally. If you want to skip just one iteration, you can use continue
.
http://php.net/manual/en/control-structures.break.php is the answer!
As simple as break;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With