PHP验证数组元素都是空的

问题描述:

I need to ensure that all the elements in my array are empty strings to process an action. The way I am currently doing it is incrementing a variable each time an element is an empty string. Then I check the value of that variable against a certain requirement N. If N is met, the action is processed. Below is the snippet of the code that checks for empty strings. I am not sure if this is the best way to do it and think there has to be a better way to do it because basically I am hard coding that value N. Can anybody else suggest another approach?

function checkErrorArray($ers) {
    $err_count = 0;
    foreach ($ers as &$value) {
        if ($value == '') {
            $err_count++;
        }
    }
    return $err_count;
}

我需要确保数组中的所有元素都是空字符串来处理动作。 我目前正在这样做的方法是每次元素为空字符串时递增变量。 然后我检查该变量的值是否符合某个要求N.如果满足N,则处理该动作。 下面是检查空字符串的代码片段。 我不确定这是否是最好的方法,并认为必须有更好的方法来做到这一点,因为基本上我很难编码这个价值N.其他人可以提出另一种方法吗? p>

  function checkErrorArray($ ers){
 $ err_count = 0; 
 foreach($ ers as& $ value){
 if($ value =='  '){
 $ err_count ++; 
} 
} 
返回$ err_count; 
} 
  code>  pre> 
  div>

Why don't you do:

function areAllEmpty($ers) {
    foreach ($ers as &$value) {
        //if a value is not empty, we return false and no need to continue iterating thru the array
        if (!empty($value)) return false;
    }
    //if got so far, then all must be empty
    return true;
}

It will not have to run through the whole array if a non-empty value is found.

You could also do a shorter version:

function areAllEmpty($ers) {
        $errs_str = implode('', $ers);//join all items into 1 string
        return empty($errs_str);
    }

Hope this helps.

Just filter it and if it is empty then ! will return true if not empty it will return false:

return !array_filter($ers);

Or if you actually need the count of empty elements then:

return count(array_diff($ers, array_filter($ers)));