检查空数组的最佳方法?

15

如何递归地检查数组是否为空,就像这个例子:

Array
(
    [product_data] => Array
        (
            [0] => Array
                (
                    [title] => 
                    [description] => 
                    [price] => 
                )

        )
    [product_data] => Array
        (
            [1] => Array
                (
                    [title] => 
                    [description] => 
                    [price] => 
                )

        )

)

数组不为空,但没有内容。如何使用简单的函数检查?

谢谢!


7
你的数组为什么有两个相同的键 product_data - codaddict
@codaddict:观察得好。 - Asif Mulla
抱歉,我只复制了示例的文本。 - comod
P.S:我喜欢这个社区比其他社区更多! - comod
11个回答

19

function is_array_empty($InputVariable)
{
   $Result = true;

   if (is_array($InputVariable) && count($InputVariable) > 0)
   {
      foreach ($InputVariable as $Value)
      {
         $Result = $Result && is_array_empty($Value);
      }
   }
   else
   {
      $Result = empty($InputVariable);
   }

   return $Result;
}

1
一个比我的解决方案更通用和容错的解决方案 :), 但是你能不能在发现非空答案后立即返回,而不是继续测试数组的其余部分呢? - David Mårtensson
2
foreach ($InputVariable as $Value) - comod
@David Martensson:只有在传递给函数的变量不是数组时,执行才会被路由到else语句。将问题中给出的数组视为一棵树,将else块视为所有叶子节点都将被评估的基本情况。 - emurano
是的,但如果它是一个数组,即使它可能已经发现它不是空的,它也会完成数组和层次结构中更高的每个数组。他的例子清楚地指出,您可以有空行,但它们仍应被视为空。 - David Mårtensson
啊,我明白你的意思。是的,你说得对。一旦你找到了一个非空元素,你就应该停止比较并返回false。我的实现会不必要地继续检查非空元素,直到遍历整个结构。 - emurano
@Sazzad Tushar Khan,感谢您发现了这个错别字。 - emurano

12

如果你的数组只有一层深度,你也可以这样做:

if (strlen(implode('', $array)) == 0)

在大多数情况下有效 :)


不是这样的。多维数组怎么样? - sonnb
3
你需要仔细阅读:一个级别(One level)不等于多维度/多级别(multi-dimension/multi level)。 - velop

8

使用array_walk_recursive的解决方案:

function empty_recursive($value)
{
        if (is_array($value)) {
                $empty = TRUE;
                array_walk_recursive($value, function($item) use (&$empty) {
                        $empty = $empty && empty($item);
                });
        } else {
                $empty = empty($value);
        }
        return $empty;
}

所有答案中最优雅的设置。 - chikamichi
这个问题的一个干净完美的解决方案。 - PHP Developer

2
短路计算已经包含在内。
function hasValues($input, $deepCheck = true) {
    foreach($input as $value) {
        if(is_array($value) && $deepCheck) {
            if($this->hasValues($value, $deepCheck))
                return true;
        }
        elseif(!empty($value) && !is_array($value))
            return true;
    }
    return false;
}

2

假设数组始终包含相同类型的数据:

function TestNotEmpty($arr) {
    foreach($arr as $item)
        if(isset($item->title) || isset($item->descrtiption || isset($item->price))
            return true;
    return false;
}

2
这是我的版本。一旦在数组中找到非空字符串,它就会停止。此外,它还正确地检查了空字符串,因此不会将0(零)视为空字符串(如果使用empty()函数,则会这样)。顺便说一下,即使仅针对字符串使用此函数,在多年的实践中也被证明是非常有价值的。
function isEmpty($stringOrArray) {
    if(is_array($stringOrArray)) {
        foreach($stringOrArray as $value) {
            if(!isEmpty($value)) {
                return false;
            }
        }
        return true;
    }

    return !strlen($stringOrArray);  // this properly checks on empty string ('')
}

0
如果有人偶然遇到这个问题并需要检查整个数组是否为NULL,也就是说,数组中的每一对都等于null,那么这是一个方便的函数。您可以非常容易地修改它,以便在任何变量返回NULL时返回true。我需要这个函数来更新某个Web表单中的用户数据,而且有可能完全为空,因此不需要执行任何SQL操作。
$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL);

function array_empty($ary, $full_null=false){
    $null_count = 0;
    $ary_count = count($ary);

    foreach($ary as $value){
        if($value == NULL){
            $null_count++;
        }
    }

    if($full_null == true){
        if($null_count == $ary_count){
            return true;
        }else{
            return false;
        }
    }else{
        if($null_count > 0){
            return true;
        }else{
            return false;
        }
    }
}

$test = array_empty($test_ary, $full_null=true);
echo $test;

0
这是一个很好的实用函数,如果数组为空,则返回true(1),否则返回false(0)
function is_array_empty( $mixed ) {
    if ( is_array($mixed) ) {
        foreach ($mixed as $value) {
            if ( ! is_array_empty($value) ) {
                return false;
            }
        }
    } elseif ( ! empty($mixed) ) {
        return false;
    }

    return true;
}

例如,给定一个多维数组:
$products = array(
    'product_data' => array(
        0 => array(
            'title' => '',
            'description' => null,
            'price' => '',
        ),
    ),
);

由于没有设置任何值,因此从 is_array_empty() 返回一个 true 值:

var_dump( is_array_empty($products) );

可以在以下链接交互式地查看此代码:http://codepad.org/l2C0Efab


0

如果传递的变量不是数组,或者任何嵌套数组包含一个值(包括假值!),则返回TRUE。否则返回FALSE。 短路。

function has_values($var) {
  if (is_array($var)) {
    if (empty($var)) return FALSE;
    foreach ($var as $val) {
      if(has_values($val)) return TRUE;
    }
    return FALSE;
  } 
  return TRUE;
}

0
$arr=array_unique(array_values($args));
if(empty($arr[0]) && count($arr)==1){
 echo "empty array";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接