Reputation: 161
I have 2 Foreach-Loops. One of them is nested inside the other, e.g.:
foreach(...){
foreach(...){
//if statement
}
}
Within the inner loop I got an if statement and if this statement returns true I want to break the inner loop and continue with the next outter loop. Is there any way to realize this? "break 2; " won't work as I need to continue with the outter loop.
Upvotes: 0
Views: 47
Reputation: 2897
Like with break
, you can add a number to continue
as well:
foreach(...) {
foreach(...) {
if (...)
continue 2;
}
// this will be skipped
}
From the docs:
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default value is 1, thus skipping to the end of the current loop.
Upvotes: 2
Reputation: 2885
Per PHP documentation, the default is 1, which only breaks out of the immediately encapsulating control struct
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.
For example, the below code:
<?php
foreach(array(1,2,3,4,5) as $num){
foreach(array('a', 'b') as $char){
if($char === 'b') {
break;
}
echo $char;
}
echo $num;
}
// Result: a1a2a3a4a5
It breaks before it prints 'b', but continues with the loop to 5.
Upvotes: 0