Chuck Le Butt Chuck Le Butt - 1 month ago 14x
PHP Question

PHP: Remove empty array elements from a multidimensional array

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 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
would output:

Array ( )

If I run

$arrayX = array_filter($arrayX);

I still get the same
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?


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

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