How to Flatten a Multidimensional Array? How to Flatten a Multidimensional Array? arrays arrays

How to Flatten a Multidimensional Array?


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;}


You can use the Standard PHP Library (SPL) to "hide" the recursion.

$a = array(1,2,array(3,4, array(5,6,7), 8), 9);$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));foreach($it as $v) {  echo $v, " ";}

prints

1 2 3 4 5 6 7 8 9 


In PHP 5.6 and above you can flatten two dimensional arrays with array_merge after unpacking the outer array with ... operator. The code is simple and clear.

array_merge(...$a);

This works with collection of associative arrays too.

$a = [[10, 20], [30, 40]];$b = [["x" => "X", "y" => "Y"], ["p" => "P", "q" => "Q"]];print_r(array_merge(...$a));print_r(array_merge(...$b));Array(    [0] => 10    [1] => 20    [2] => 30    [3] => 40)Array(    [x] => X    [y] => Y    [p] => P    [q] => Q)

In PHP 8.0 and below, array unpacking does not work when the outer array has non numeric keys. Support for unpacking array with string keys is available from PHP 8.1. To support 8.0 and below, you should call array_values first.

$c = ["a" => ["x" => "X", "y" => "Y"], "b" => ["p" => "P", "q" => "Q"]];print_r(array_merge(...array_values($c)));Array(    [x] => X    [y] => Y    [p] => P    [q] => Q)

Update: Based on comment by @MohamedGharib

This will throw an error if the outer array is empty, since array_merge would be called with zero arguments. It can be be avoided by adding an empty array as the first argument.

array_merge([], ...$a);


matomo