如果我有一个数组:
$nav = array($nav_1, $nav_2, $nav_3);
并且想要检查它们是否为空(带有循环)(真实数组要大得多),以便它分别检查每个变量,我该怎么做?
我想要这样的东西;
$count = 0;
while(count < 3){
if(empty($nav[$count])) //the loops should go through each value (nav[0], nav[1] etc.)
//do something
$count = $count+1;
}else{
//do something
$count = $count+1;
}
}
答案 0 :(得分:4)
非常直接的foreach
循环:
$count = 0;
foreach ($nav as $value) {
if (empty($value)) {
// empty
$count++;
} else {
// not empty
}
}
echo 'There were total ', $count, ' empty elements';
如果您要检查所有值是否为空,请使用array_filter()
:
if (!array_filter($nav)) {
// all values are empty
}
答案 1 :(得分:0)
使用以下代码,您可以检查阵列中的所有变量是否为空。这是你在找什么?
$eachVarEmpty = true;
foreach($nav as $item){
// if not empty set $eachVarEmpty to false and go break of the loop
if(!empty(trim($item))){
$eachVarEmpty = false;
// go out the loop
break;
}
}
答案 2 :(得分:0)
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);