Search code examples
phpwhile-loopforeach

php while loop inside foreach only executes on first loop


I have an array of values and I use a while loop to lookup a CSV file for each of those values and make a list of any matches

But, for some reason the while loop only executes for the first foreach loop - all subsequent loops just exit with nothing ---

        foreach ($selectedpaths as $path) {
            
            echo "<BR>working on this: " . $path . "<BR>";      

            #run through the csv
            while ($row = fgetcsv($allroutes)) {            
                
                echo ".";               

                #fetch entries that match
                if ($row[5] == $path) {
                    echo "<BR>" .$row[5] . " == " . $path ."    MATCH   " . $row . "<BR>";
                }
            }
        }

This is the output from that code:

working on this: test1
.....................................................................................
test1 == test1 MATCH A1,B1,C1,D1,E1,test1
........................................
test1 == test1 MATCH A6,B6,C6,D6,E1,test1
.......................................................................
test1 == test1 MATCH A68,B68,C68,D68,E1,test1
..............................................................................................................................................................................................................
working on this: test2

working on this: test3

working on this: test4

I can see from the "working on this: X" that it definitely is looping through each of the lookups in turn

But even if it finds no matches, it should still be outputting the dots to say its at least looping though the csv to try..... but it outputs nothing after the first loop

I would understand if it never worked but why does it work the first time round? Is it something weird about how php executes while loops?


Solution

  • The file pointer already reached the end of the file the first time around, so this has no more rows to return:

    fgetcsv($allroutes)
    

    Presumably somewhere before this you called something like this to open the file stream:

    $allroutes = fopen("some_file.csv", "r")
    

    You could rewind the stream to the start of the file before trying to loop over it again:

    rewind($allroutes);
    // the while loop here
    

    Or potentially move the entire file-opening operation into the foreach loop:

    $allroutes = fopen("some_file.csv", "r")
    // the while loop here
    

    (The latter approach is probably slower. For small scales the difference is likely negligible and can be weighed against the clarity of the surrounding logic.)