Reputation: 6509
I have a CSV (attached below) that I am looping through with PHP. Note: the Peter
entry is missing an Extension
number.
How do I break the loop if any $cell (like Extension
) is empty
<?php
echo "<html><body><table>\n\n";
$f = fopen("users.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
~
Forename,Surname,Extension
Jim,Carey,1973
Peter,Robertson,
Upvotes: 1
Views: 3945
Reputation: 569
Try using this -
<?php
echo "<html><body><table>\n\n";
$f = fopen("users.csv", "r");
while (($line = fgetcsv($f)) !== false) {
$row = "<tr>";
$is_empty = false;
foreach ($line as $cell) {
if ($cell !== '') {
$row .= "<td>" . htmlspecialchars($cell) . "</td>";
} else {
$is_empty = true;
}
}
$row .= "</tr>\n";
if ($is_empty) {
continue;
} else {
echo $row;
}
}
fclose($f);
echo "\n</table></body></html>";
?>
This solution will print the row only if all the fields have value. You can use break instead of continue, if you want to break the loop.
Upvotes: 3