Filtering Multi-Dimensional Arrays in PHP

Filtering empty values from an array in PHP is best done using array_filter(). Let’s take a simple array, for example:

Now, let’s run it through array_filter():

What we end up with is this:

Awesome! Now what happens when we need to filter this array?

Well, PHP doesn’t provide a way to recursively filter a multi-dimensional array.

Here is a simple utility function that works exactly like array_filter(), but is recursive:

The function works just like PHP’s array_filter() and even allows for a custom callback if you want to provide one. Running our multidimensional array through array_filter_recursive() returns this result:

2 thoughts on “Filtering Multi-Dimensional Arrays in PHP”

  1. Add recursive function :

    $value = call_user_func(__FUNCTION__, $value, $callback);

    if (empty($value)) {
    return array_filter_recursive($array, $callback);
    }

Leave a Reply

Your email address will not be published. Required fields are marked *