How to remove empty values from multidimensional array in PHP?

Richard-MX picture Richard-MX · Apr 18, 2012 · Viewed 11.9k times · Source

I've been looking a lot of answers, but none of them are working for me.

This is the data assigned to my $quantities array:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array([35.00] => )
    [1] => Array([30.00] => )
    [2] => Array([30.00] => )
)

I'm looking for a way to remove the subarrays with empty values like [12] [1] and [2] while keeping everything else.

The desired result:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
)

I tried a lot of the functions on the official php docs and none of them worked.

I've used this one:

function array_filter_recursive($array, $callback = null) {
    foreach ($array as $key => & $value) {
        if (is_array($value)) {
            $value = array_filter_recursive($value, $callback);
        } else {
            if ( ! is_null($callback)) {
                if ( ! $callback($value)) {
                    unset($array[$key]);
                }
            } else {
                if ( ! (bool) $value) {
                    unset($array[$key]);
                }
            }
        }
    }
    unset($value);
    return $array;
}

But it only removes the element in the subarrays; I need the subarrays to be removed entirely.

I don't want this:

Array(
    [10] => Array([25.00] => 1)
    [9] => Array([30.00] => 3)
    [8] => Array([30.00] => 4)
    [12] => Array()
    [1] => Array()
    [2] => Array()
)

Answer

Alastair F picture Alastair F · Sep 14, 2013

Bit late, but may help someone looking for same answer. I used this very simple approach to;

  1. remove all the keys from nested arrays that contain no value, then
  2. remove all the empty nested arrays.

$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );