我需要确保数组中的所有元素都是空字符串来处理操作。我目前的做法是,每当元素为空字符串时,就增加一个变量。然后,我根据某个要求N检查该变量的值。如果满足N,则处理该操作。下面是检查空字符串的代码片段。我不确定这是否是最好的方法,我认为必须有更好的方法来做到这一点,因为基本上我正在硬编码N值。其他人能建议另一种方法吗?
function checkErrorArray($ers) {
$err_count = 0;
foreach ($ers as &$value) {
if ($value == '') {
$err_count++;
}
}
return $err_count;
}
为什么不这样做:
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);
}
希望这能有所帮助。
只需过滤它,如果它为空,则!
将返回true
,如果不为空,将返回false
:
return !array_filter($ers);
或者,如果你真的需要空元素的计数,那么:
return count(array_diff($ers, array_filter($ers)));