【问题标题】:How to check each value in an array is empty?如何检查数组中的每个值是否为空?
【发布时间】:2014-01-18 10:57:34
【问题描述】:

如果我有一个数组:

$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;
     }
}

【问题讨论】:

  • 你可以使用in_array() ?

标签: php arrays loops


【解决方案1】:

foreach 循环非常简单:

$count = 0;
foreach ($nav as $value) {
    if (empty($value)) {
        // empty
        $count++;
    } else {
        // not empty
    }
}

echo 'There were total ', $count, ' empty elements';

如果您要检查 all 值是否为空,请使用array_filter()

if (!array_filter($nav)) {
    // all values are empty
}

【讨论】:

  • 我还要对 OP 说,根据您的阵列的构建方式,您可能需要清理和清理字符串,以减少写入空格之类的内容并让您在以后更头痛。
【解决方案2】:

使用以下代码,您可以检查数组中的所有变量是否为空。这是你要找的吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-21
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多