简体   繁体   English

如果变量为空,则在循环时断开PHP

[英]Break PHP while loop if variable is empty

I have a CSV (attached below) that I am looping through with PHP. 我有一个CSV(附在下面),我正在使用PHP循环。 Note: the Peter entry is missing an Extension number. 注意: Peter条目缺少Extension号码。

How do I break the loop if any $cell (like Extension ) is empty 如果任何$ cell(如Extension )为空,我该如何打破循环

<?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. 如果要打破循环,可以使用break而不是continue。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM