Reputation: 115
So, I've been experimenting with foreach
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.
Upvotes: 0
Views: 98
Reputation: 8706
This is why all control blocks (ifs and loops) should be wrapped in braces... Your code is only looping the first statement immediately following the foreach.
$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>";
}
?>
Upvotes: 1
Reputation: 2782
Try to do like this, In your current syntax it will consider on first line as the part of foreach body, this is the reason it is echoing only last line of you CSV file.
<?php
$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>";
}
?>
Upvotes: 1
Reputation: 32066
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>";
}
Upvotes: 2