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,
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.