Chuck Le Butt Chuck Le Butt - 1 year ago 145
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?

Answer Source

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

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download