Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP array_filter_recursive function
<?php
/** function array_filter_recursive
*
* Exactly the same as array_filter except this function
* filters within multi-dimensional arrays
*
* @param array
* @param string optional callback function name
* @param bool optional flag removal of empty arrays after filtering
* @return array merged array
*/
function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false) {
foreach ($array as $key => & $value) { // mind the reference
if (is_array($value)) {
$value = array_filter_recursive($value, $callback);
if ($remove_empty_arrays && ! (bool) $value) {
unset($array[$key]);
}
}
else {
if ( ! is_null($callback) && ! $callback($value)) {
unset($array[$key]);
}
elseif ( ! (bool) $value) {
unset($array[$key]);
}
}
}
unset($value); // kill the reference
return $array;
}
@vanderlee

This comment has been minimized.

Copy link

commented Jun 23, 2016

Fix $remove_empty_arrays in recursion and added $key to callback argument list:

/** function array_filter_recursive
 *
 *      Exactly the same as array_filter except this function
 *      filters within multi-dimensional arrays
 *
 * @param array
 * @param string optional callback function name
 * @param bool optional flag removal of empty arrays after filtering
 * @return array merged array
 */
function array_filter_recursive($array, $callback = null, $remove_empty_arrays = false)
{
    foreach ($array as $key => & $value) { // mind the reference
        if (is_array($value)) {
            $value = array_filter_recursive($value, $callback, $remove_empty_arrays);
            if ($remove_empty_arrays && !(bool) $value) {
                unset($array[$key]);
            }
        } else {
            if (!is_null($callback) && !$callback($value, $key)) {
                unset($array[$key]);
            } elseif (!(bool) $value) {
                unset($array[$key]);
            }
        }
    }
    unset($value); // kill the reference
    return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.