检查表的3列是否为空或已设置的优雅方法


Elegant way of checking if 3 columns of a table are empty or set

我需要写一个函数,检查表的3列是否为空或设置。我的代码工作,但我认为它不是很优雅。因为如果你想检查4列,你必须重写整个代码。你能以一种优雅的方式重写这段代码吗?

                //row[0] == id 
                //row[1] == licensekey 
                //row[2] == url_1 
                //row[3] == url_2 
                //row[4] == url_3
            if($row[2] == '' && $row[3] == '' && $row[4] == ''){
                echo 'Every row is empty';
            }
            if($row[2] == '' && $row[3] == '' && $row[4] != ''){
                echo 'Row 1 and 2 are empty';
            }
            if($row[2] == '' && $row[3] != '' && $row[4] != ''){
                echo 'Row 1 is empty';
            }
            if($row[2] != '' && $row[3] == '' && $row[4] == ''){
                echo 'Row 2 and 3 are empty';
            }
            if($row[2] != '' && $row[3] != '' && $row[4] == ''){
                echo 'Row 3 is empty';
            }
            if($row[2] != '' && $row[3] != '' && $row[4] != ''){
                echo 'Every row is set';
            }
    $empty = [];
    foreach ($row as $i => $val) {
        if (!$val) {
            $empty[] = $i;
        }
    }
    if ($empty) {
        $msg = 'Row ' . implode(' and ', $empty) . ' are (is) empty';
    } else {
        $msg = 'Every row is set';
    }
    echo $msg;

这应该适用于任何长度的行

function checkRow($row)
{
    $st = "";
    foreach($row as $key => $col)
    {
        if($col == '')
        {
            if($st) 
                $st .= " and ";
            $st .= "Column $key is empty ";
        }
    }
    if(!$st)
        $st = 'Every col is set';
    return $st;
}

既然你的问题似乎是学术性的:

根据你想达到的目标,有两种不同的答案。

  1. 只对空列的特定组合执行操作
  2. 对每一列做一些特定的操作,如果它是空的

您的示例看起来像变体2,因为您只是打印该特定列为空。在本例中,你可以这样写

if($row[2] == ''){
   echo 'Row 2 is empty'
}
if($row[3] == ''){
   echo 'Row 3 is empty'
}
然而,

变体1意味着您只想做某事,当假设只有第2列和第3列为空而其他列不是时。在这种情况下,你唯一的机会就是按你的方式去做。为了使代码看起来更简洁,您应该编写如下函数:

//pseudo code:
function boolean isEmpty($column){
   if($column == ''){
      return true;
   } else {
      return false;
   }
}

并在if中调用