Skip to content

Instantly share code, notes, and snippets.

@kohnmd
Last active September 20, 2021 12:48
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kohnmd/11197713 to your computer and use it in GitHub Desktop.
Save kohnmd/11197713 to your computer and use it in GitHub Desktop.
Function to recursively flatten multidimensional PHP array.
<?php
// Requires PHP 5.3+
// Found here: http://stackoverflow.com/a/1320156
function flatten_array(array $array) {
$flattened_array = array();
array_walk_recursive($array, function($a) use (&$flattened_array) { $flattened_array[] = $a; });
return $flattened_array;
}
@mattxtlm
Copy link

mattxtlm commented Jan 3, 2017

@zdenko:

You should include type hinting to avoid possible type errors. Slightly modified:

function flatten(array $arr) {
        return array_reduce($arr, function ($c, $a) { 
		return is_array($a) ? array_merge($c, flatten($a)) : array_merge($c, [$a]);

},
[]); 
    }

@ultrasamad
Copy link

@Zenko:
If you pass arguments of a function (using func_get_args() which returns an array) to the function you run into Maxium memory exceeded error. How to fix please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment