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:

$data = array( null, true, false, 0, 1, 11, '', 'test' );

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

array_filter( $data );

What we end up with is this:

array( true, 1, 11, 'test' );

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

$data = array(
    null,
    true,
    false,
    0,
    1,
    11,
    '',
    'test',
    <span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre="param "><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre="param ">array(),
    array</span></span></span></span>(
        null,
        true,
        false,
        0,
        1,
        11,
        '',
        'test',
        array(),
        array(
            null,
            true,
            false,
            0,
            1,
            11,
            '',
            'test',
            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:

/**
 * Recursively filter an array
 *
 * @param array $array
 * @param callable $callback
 *
 * @return array
 */
function array_filter_recursive( array $array, callable $callback = null ) {
    $array = is_callable( $callback ) ? array_filter( $array, $callback ) : array_filter( $array );
    foreach ( $array as &$value ) {
        if ( is_array( $value ) ) {
            $value = call_user_func( __FUNCTION__, $value, $callback );
        }
    }

    return $array;
}

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:

array(
    true,
    1,
    11,
    'test',
    array(
        true,
        1,
        11,
        'test',
        array(
            true,
            1,
            11,
            'test',
        ),
    ),
);

Comments

  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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.