michaelmcgurk michaelmcgurk - 1 year ago 94
PHP Question

Break PHP while loop if variable is empty

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,

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download