PHP验证数组元素都是空的

时间:2016-03-26 20:17:52

标签: php arrays

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

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

2 个答案:

答案 0 :(得分:3)

为什么不做:

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;
}

如果找到非空值,则不必遍历整个数组。

你也可以做一个更短的版本:

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

希望这有帮助。

答案 1 :(得分:2)

只需过滤它,如果它是空的,那么!将返回true如果不为空,它将返回false

return !array_filter($ers);

或者,如果你真的需要空元素的数量,那么:

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