Phpinspectionsea: False-positive: loop does not loop with multidimensional continue

Created on 15 Feb 2017  路  4Comments  路  Source: kalessil/phpinspectionsea

I have the following code:

$values = [
    [ 1, '', '' ],
    [ '', '', 6 ],
    [ 7, '', '' ],
    [ '', '', '' ],
    [ '', 8, '' ],
];

foreach ($values as $key => $subValues) {
    foreach ($subValues as $subValue) {
        if (is_int($subValue)) {
            printf("%s\n", $subValue);
            continue 2;
        }
    }

    printf("Found nothing at index %u\n", $key);
    break;
}

What is code does is: foreach() $values multidimensional array. Then foreach() this array elements too, and search for first ocurrency of an _int_, print, then continue 2 (it's, make the first foreach() continue, instead of currently). If nothing is found, then it advances to next first foreach() statements. The result should be: "1, 6, 7. Found nothing at index 3" (then it should be break, and "8" will not be printed).

Then you can see that the first foreach() does looping, because it is looped by the continue 2. It is happening with for() too, or by using return instead of break on first looping.

The solution here is something like that: if your foreach() could be a "does not loop", check by existence of a internal continue N, where N is the distance between your looping and the internal loopings.

The code bellow should be valid too, for instance:

foreach ($a as $av) {
    foreach ($b as $bv) {
        foreach ($c as $cv) {
            continue 3; // => Distance for first looping.
        }

        break; // Warning: really doesn't loop.
    }

    break; // Valid: does loop because continue 3.
}

PS.: add a label called "false-positive", please.

bug / false-positive fixed

All 4 comments

false-positive = bug )

@rentalhost : a fresh binary pushed, so you can give the fix a try.

@kalessil Works like a charm! Thanks!

Super, thanks for checking ;)

Was this page helpful?
0 / 5 - 0 ratings