php 检查空数组的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4014327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:44:09  来源:igfitidea点击:

best way to check a empty array?

phparraysrecursion

提问by comod

How can I check an array recursively for empty content like this example:

如何递归地检查数组中的空内容,如下例所示:

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

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

        )

)

The array is not empty but there is no content. How can I check this with a simple function?

数组不为空但没有内容。我怎样才能用一个简单的函数来检查这个?

Thank!!

谢谢!!

回答by emurano


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

回答by marcovtwout

If your array is only one level deep you can also do:

如果您的阵列只有一层深,您还可以执行以下操作:

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

Works in most cases :)

在大多数情况下工作:)

回答by Milan Majer

Solution with array_walk_recursive:

使用 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;
}

回答by David M?rtensson

Assuming the array will always contain the same type of data:

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

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

回答by Patrick

Short circuiting included.

包括短路。

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

回答by Lukas

Here's my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.

这是我的版本。一旦它在数组中找到一个非空字符串,它就会停止。此外,它会正确检查空字符串,因此 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 ('')
}

回答by Santosh

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

回答by Tigran

Returns TRUEif passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSEotherwise. Short circuits.

返回TRUE如果传递了一个变量以外的阵列,或者如果任何嵌套阵列包含一个值(包括falsy值!)。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;
}

回答by rjb

Here's a good utility function that will return true (1)if the array is empty, or false (0)if not:

这是一个很好的实用函数,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;
}

For example, given a multidimensional array:

例如,给定一个多维数组:

$products = array(
    'product_data' => array(
        0 => array(
            'title' => '',
            'description' => null,
            'price' => '',
        ),
    ),
);

You'll get a truevalue returned from is_array_empty(), since there are no values set:

您将获得true从 返回的值is_array_empty(),因为没有设置值:

var_dump( is_array_empty($products) );

View this code interactively at: http://codepad.org/l2C0Efab

以交互方式查看此代码:http: //codepad.org/l2C0Efab

回答by phse

I needed a function to filter an array recursively for non empty values.

我需要一个函数来递归过滤非空值的数组。

Here is my recursive function:

这是我的递归函数:

function filterArray(array $array, bool $keepNonArrayValues = false): array {
  $result = [];
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $value = $this->filterArray($value, $keepNonArrayValues);
    }

    // keep non empty values anyway
    // otherwise only if it is not an array and flag $keepNonArrayValues is TRUE 
    if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
      $result[$key] = $value;
    }
  }

  return array_slice($result, 0)
}

With parameter $keepNonArrayValuesyou can decide if values such 0(number zero), ''(empty string) or false(bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = trueonly empty arrays will be removed from target array.

使用参数,$keepNonArrayValues您可以决定是否将0(数字零)、''(空字符串)或false(bool FALSE)等值保留在数组中。换句话说:如果$keepNonArrayValues = true只从目标数组中删除空数组。

array_slice($result, 0)has the effect that numeric indices will be rearranged (0..length-1).

array_slice($result, 0)具有将重新排列数字索引的效果 (0..length-1)。

Additionally, after filtering the array by this function it can be tested with empty($filterredArray).

此外,通过此函数过滤数组后,可以使用empty($filterredArray).