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?
2
Answers
The file pointer already reached the end of the file the first time around, so this has no more rows to return:
Presumably somewhere before this you called something like this to open the file stream:
You could rewind the stream to the start of the file before trying to loop over it again:
Or potentially move the entire file-opening operation into the
foreach
loop:(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.)
As you read the file inside the loop, the next time you would have to read the file again for the next comparison.
It looks like if you could read the file and just checking if the path is in the list of paths (using
in_array()
)…with this method, you don’t need the outer loop.