I am writing some code which will frequently contain loops that I need to break out of under certain conditions. The problem is that sometimes, I am nested 3 levels deep, some times 4 and some times 5 or more.
I could break out by writing break 3
, break 4
and break 5
etc. but that requires me to keep track of the current depth inside each nested loop. Is there an easier way of breaking out of unknown number of nested loops without using goto
?
I think the question needs a little more explanation.
for
loops in part of a code.for
loops.for
loops.There are all independent of each other and I only have to go through one of them for each run of the code. The one I loop through depends on value of certain parameters.
I could break out of them by keeping track of for
loops in each case and using break number
but doing it for 100-200 different sets of nested for
loops is tiring. It will also not work if the number of nested loops have to be updated.
I was hoping that there is some code in PHP which could just break out of all loops at once without me keeping track.
If you know the depth of the loop you want to break out of, but not how many levels down you are from that, you can use a variable that each loop checks.
$break_level = 99;
while (...) {
while (...) {
while (...) {
while (...) {
...
if (...) {
$break_level = 2;
break;
}
...
}
if ($break_level <= 3) {
break;
}
}
if ($break_level <= 2) {
break;
}
}
if ($break_level <= 1) {
break;
}
}
But this kind of generality is hardly ever needed. I've written millions of loops in my lifetime, and I hardly ever need to break out of anything other than the current loop, its immediate container, or the entire set of nested loops. In these cases there's often a variable that can be checked. For instance, if you're searching a multidimensional array, just set a $found
variable:
$found = false;
foreach ($array as $level1) {
foreach ($level1 as $level2) {
if (...) {
$found = true;
break;
}
}
if ($found) {
break;
}
}