best way to check a empty array?

Viewed 25017

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

11 Answers

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

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).

Related