Last active
April 25, 2026 23:24
-
-
Save benjamw/1690140 to your computer and use it in GitHub Desktop.
PHP array_filter_recursive function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Exactly the same as array_filter except this function | |
| * filters within multidimensional arrays | |
| * | |
| * @param array $array | |
| * @param callable|null $callback optional filter callback function | |
| * @param bool $remove_empty_arrays optional flag removal of empty arrays after filtering | |
| * | |
| * @return array filtered array | |
| */ | |
| function array_filter_recursive(array $array, callable $callback = null, bool $remove_empty_arrays = false): array { | |
| foreach ($array as $key => & $value) { // mind the reference | |
| if (is_array($value)) { | |
| $value = call_user_func_array(__FUNCTION__, array($value, $callback, $remove_empty_arrays)); | |
| 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Version from tiria-fred
Added
$modeargument like originalyarray_filterand added additional flag to include$arrayin callback argument listUsage:
array_filtermodes and bitwise orARRAY_FILTER_INCLUDE_ARRAY