MissDizy MissDizy - 7 months ago 14
PHP Question

For each loop in php

So, I've been experimenting with for each loops in php as a way of reading and displaying the contents of a csv file. This is what I have so far:

$file = file("games.csv");
foreach($file as $k)
$csv = explode(',',$k);
echo "<tr>
<td>$csv[0]</td>
<td>$csv[1]</td>
<td>$csv[2]</td>
<td>$csv[3]</td>
<td>$csv[4]</td>
</tr>";

?>


It works but only displays the last record in the csv file. Why is this? Until I can understand why, I don't think I can fix the issue and display all records

Answer

Add curly braces { } around the body of your foreach. The syntax you're using means only the first line gets looped.

foreach($file as $k) {
    $csv = explode(',',$k);
    echo "<tr> 
        <td>$csv[0]</td>
        <td>$csv[1]</td>
        <td>$csv[2]</td>
        <td>$csv[3]</td>
        <td>$csv[4]</td>
        </tr>";
}
Comments