If I have an array:
如果我有一个数组:
$nav = array($nav_1, $nav_2, $nav_3);
and want to check if they are empty with a loop (the real array is much bigger), so that it checks each variable separately, how do I do it?
并且要检查它们是否为空的循环(实际数组要大得多),以便它分别检查每个变量,我该如何做呢?
I want something like this;
我想要这样的东西;
$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;
}
}
3 个解决方案
#1
4
Pretty straight-forward with a foreach
loop:
非常直接的foreach循环:
$count = 0;
foreach ($nav as $value) {
if (empty($value)) {
// empty
$count++;
} else {
// not empty
}
}
echo 'There were total ', $count, ' empty elements';
If you're trying to check if all the values are empty, then use array_filter()
:
如果您试图检查所有的值是否为空,则使用array_filter():
if (!array_filter($nav)) {
// all values are empty
}
#2
0
With the following code you can check if all variables are empty in your array. Is this what you are looking for?
使用以下代码,您可以检查数组中的所有变量是否为空。这就是你要找的吗?
$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;
}
}
#3
0
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);
#1
4
Pretty straight-forward with a foreach
loop:
非常直接的foreach循环:
$count = 0;
foreach ($nav as $value) {
if (empty($value)) {
// empty
$count++;
} else {
// not empty
}
}
echo 'There were total ', $count, ' empty elements';
If you're trying to check if all the values are empty, then use array_filter()
:
如果您试图检查所有的值是否为空,则使用array_filter():
if (!array_filter($nav)) {
// all values are empty
}
#2
0
With the following code you can check if all variables are empty in your array. Is this what you are looking for?
使用以下代码,您可以检查数组中的所有变量是否为空。这就是你要找的吗?
$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;
}
}
#3
0
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);