Paulund

Flatten Nested Arrays With PHP

Here is a quick code snippet for flattening a multi-dimensional array using PHP.

This uses the function array_walk_recursive that applies a function to every element of an array. Using this function we can add the value to a new array and return that instance.

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}
print_r(flatten([1, 2, [3], [4, [5, 6], 5, 6], [[7], [8, [9]]], 10, [[[11], 12]]]));

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 5
    [7] => 6
    [8] => 7
    [9] => 8
    [10] => 9
    [11] => 10
    [12] => 11
    [13] => 12
)