How to Flatten a Multidimensional Array?

Alix Axel picture Alix Axel · Aug 24, 2009 · Viewed 264.2k times · Source

Is it possible, in PHP, to flatten a (bi/multi)dimensional array without using recursion or references?

I'm only interested in the values so the keys can be ignored, I'm thinking in the lines of array_map() and array_values().

Answer

too much php picture too much php · Aug 24, 2009

As of PHP 5.3 the shortest solution seems to be array_walk_recursive() with the new closures syntax:

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}