This is likely very trivial but I haven't been able to figure it out.
This works:
function MyFunction(){
//Do stuff
}
foreach($x as $y){
MyFunction();
if($foo === 'bar'){continue;}
//Do stuff
echo $output . '<br>';
}
But this doesn't:
function MyFunction(){
//Do stuff
if($foo === 'bar'){continue;}
}
foreach($x as $y){
MyFunction();
//Do stuff
echo $output . '<br>';
}
That yields only 1 $output and then:
Fatal error: Cannot break/continue 1 level
Any idea what I'm doing wrong?
Introduction. The continue statement is one of the looping control keywords in PHP. When program flow comes across continue inside a loop, rest of the statements in current iteration of loop are skipped and next iteration of loop starts. It can appear inside while, do while, for as well as foreach loop.
The PHP continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. The continue statement is used within looping and switch control structure when you immediately jump to the next iteration.
To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.
The break statement terminates the whole iteration of a loop whereas continue skips the current iteration. The break statement terminates the whole loop early whereas the continue brings the next iteration early.
You can't break/continue a loop outside a function, from within a function. However, you can break/continue your loop based on the return value of your function:
function myFunction(){
//Do stuff
return $foo === 'bar';
}
foreach($x as $y) {
if(myFunction()) {
continue;
}
//Do stuff
echo $output . '<br>';
}
The continue
statement is valid inside looping structures only.
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