Thursday, November 14, 2019

Is there a "superbreak" in Javascript or PHP for loops?




On many of the projects on which I work, I find that I have nested for loops (I will focus on PHP implementation but applies to javascript as well) that take this generic form:



$array1 = array(........);
$count1 = count($array1);

$invalidState = false;//An invalid state will be looked for in the innermost loop, and if found, break all the loops

for($i = 0; $i < $count1; $i++) {
//parsing, then another loop

$array2 = explode("needle", $array1[$i]);
$count2 = count($array2);
for($j = 0; $j < $count2; $j++) {
//parsing, then sometimes even another another loop
$array3 = explode("different-needle", $array2[$j]);
$count3 = count($array3);
for($k = 0; $k < $count3; $k++) {
//check for an invalid state in $array3[$k], and break if invalid state = true;
}
if ($invalidState) break;

}
if ($invalidState) break;
}


To reiterate, if an invalid state is found in the innermost loop, then all the loops should break. But as far as I am aware, to break from all the loops, I must set a variable (in this case $invalidState), and check this in all the outer loops, and if true, then break.



Is there any kind of "super-break" where if a condition is met in the innermost loop, all outer loops will be broken?


Answer



Yes, try this:




for($i = 0; $i < $count1; $i++) {
//parsing, then another loop
$array2 = explode("needle", $array1[$i]);
$count2 = count($array2);
for($j = 0; $j < $count2; $j++) {
//parsing, then sometimes even another another loop
$array3 = explode("different-needle", $array2[$j]);
$count3 = count($array3);
for($k = 0; $k < $count3; $k++) {

break 3;

}
if ($invalidState) break;
}
if ($invalidState) break;
}


When you write break n you are breaking n nested loops.

However, you can't break $foo, because this ability has been recently removed:



http://php.net/manual/en/control-structures.break.php


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...