Recursively remove empty elements and subarrays from a multi-dimensional array

Chuck Le Butt picture Chuck Le Butt · Mar 27, 2012 · Viewed 27k times · Source

I can't seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.

My input array may look like this:

Array ( [0] => Array ( [Name] => [EmailAddress] => ) ) 

(And so on, if there's more data, although there may not be...)

If it looks like the above, I want it to be completely empty after I've processed it.

So print_r($array); would output:

Array ( )

If I run $arrayX = array_filter($arrayX); I still get the same print_r output. Everywhere I've looked suggests this is the simplest way of removing empty array elements in PHP5, however.

I also tried $arrayX = array_filter($arrayX,'empty_array'); but I got the following error:

Warning: array_filter() [function.array-filter]: The second argument, 'empty_array', should be a valid callback

What am I doing wrong?

Answer

Wesley Murch picture Wesley Murch · Mar 27, 2012

Try using array_map() to apply the filter to every array in $array:

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

Demo: http://codepad.org/xfXEeApj