2014-01-18 51 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);