Flattening a Multidimensional Array in PHP


Flatten an array with array_reduce() and array_merge().

Source Code

function flatten($array) {
    return array_reduce($array, function ($carry, $item) {
        return array_merge($carry, (array)$item);
    }, []);
}
$multi = [[1, 2], [3, 4], [5, 6]];
$flat = flatten($multi);
print_r($flat);
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments