best way to check a empty array?

后端 未结 11 1122
难免孤独
难免孤独 2020-11-30 10:16

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

Array
(
    [product_data] => Array
        (
            [0] => Array
               


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 11:06

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

提交回复
热议问题