Never Use array_merge in a Loop

The spread operator to the rescue.

Flattening a one-level array

$lists = [
[1, 2],
[3, 4],
[5, 6],
];
$merged = [];foreach($lists as $list) {
$merged = array_merge($merged, $list);
}
// $merged === [1, 2, 3, 4, 5, 6];
$lists = [
[1, 2],
[3, 4],
[5, 6],
];
$merged = array_merge(...$lists);
// === [1, 2, 3, 4, 5, 6];

Unpacking an assoc-array

$lists = [
'key-1' => [1, 2],
'key-2' => [3, 4],
'key-3' => [5, 6],
];
$merged = array_merge(...array_values($lists));
// === [1, 2, 3, 4, 5, 6];

No loops & no more performance problem.

Flatting a multilevel array

$lists = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []];
$lists = [
'key-1' => [
1,
[2],
'key-2' => [
3,
[
'key-3' => [4, 5],
],
],
],
6,
'key-4' => [7, 8],
];
$merged = iterator_to_array(
new RecursiveIteratorIterator(
new RecursiveArrayIterator($lists)
),
$use_keys = false
);
// $merged === [1, 2, 3, 4, 5, 6, 7, 8];

Conclusion

$flattenList = array_merge(...array_values($lists));

Aka: Chema. I love writing about stuff that I find interesting and bring some value to my life, so I can share them with you. https://chemaclass.es

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store