I have the following loop and I want to continue
the while loop when the check inside the inner loop has meet the condition. I found a solution here (which is I applied in the following example), but it is for c#
.
$continue = false;
while($something) {
foreach($array as $value) {
if($ok) {
$continue = true;
break;
// continue the while loop
}
foreach($value as $val) {
if($ok) {
$continue = true;
break 2;
// continue the while loop
}
}
}
if($continue == true) {
continue;
}
}
Is PHP has its own built it way to continue
the main loop when the inner loops have been break
-ed out?
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
Break out of nested loops with else and continue You can break all loops with else and continue . The code with explanation is as follows. When the inner loop ends normally without break , continue in the else clause is executed.
The break statement is used to ends the execution of the current loop or switch case statement in PHP. But when working with nested loops and wants to exit out from all or some of the outer loops. For this, you need to pass numeric value following with break statement.
After reading the comment to this question (which was deleted by its author) and did a little research, I found that there is also parameter for continue
just like break
. We can add number to the continue
like so:
while($something) {
foreach($array as $value) {
if($ok) {
continue 2;
// continue the while loop
}
foreach($value as $val) {
if($ok) {
continue 3;
// continue the while loop
}
}
}
}
I think as you are not running the continue
until you have processed the complete inner foreach it is irrelevant. You need to execute the continue
in situ and not wait until the end of the loop.
Change the code to this
while($something) {
foreach($array as $value) {
if($ok) {
continue; // start next foreach($array as $value)
}
foreach($value as $val) {
if($ok) {
break 2; // terminate this loop and start next foreach($array as $value)
}
}
}
}
RE: Your comment
while($something) {
if($somevalue) {
// stop this iteration
// and start again at iteration + 1
continue;
}
}
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