best way to check a empty array?

妖精的绣舞 提交于 2019-12-28 04:07:29

问题


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!!


回答1:



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



回答2:


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

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

Works in most cases :)




回答3:


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



回答4:


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



回答5:


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



回答6:


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.

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 ('')
}



回答7:


If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any 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;



回答8:


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



回答9:


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

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



回答10:


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

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 true value returned from is_array_empty(), since there are no values set:

var_dump( is_array_empty($products) );

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




回答11:


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 $keepNonArrayValues you 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 = true only empty arrays will be removed from target array.

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

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



来源:https://stackoverflow.com/questions/4014327/best-way-to-check-a-empty-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!