2014-01-18 47 views
2

如果我有一个数组:如何检查数组中的每个值是否为空?

$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

你可以用'in_array()'? –

回答

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

我也会对OP说,取决于你的数组是如何构建的,你可能需要清理和清理字符串,而不是像写入空白那样的东西,并且让你头痛得更远。 – Ohgodwhy

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; 
    } 
} 
0
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);