3v4l.org

run code in 300+ PHP versions simultaneously
<?php function initArray() { $arr = []; for ($i = 0; $i < 20000; $i++) { $arr[] = ['name' => 'John', 'email' => 'john@me.com']; } return $arr; } function flatten1($array, $depth = INF) { $result = []; foreach ($array as $item) { $item = $item instanceof Collection ? $item->all() : $item; if (! is_array($item)) { $result[] = $item; } else { $values = $depth === 1 ? array_values($item) : flatten1($item, $depth - 1); foreach ($values as $value) { $result[] = $value; } } } return $result; } function flatten2($array, $depth = INF) { $result = []; foreach ($array as $item) { $item = $item instanceof Collection ? $item->all() : $item; if (! is_array($item)) { $result[] = $item; } else { $values = $depth === 1 ? array_values($item) : flatten2($item, $depth - 1); array_push($result, ...$values); } } return $result; } echo PHP_EOL."CONCAT".PHP_EOL; $arr = initArray(); $start = microtime(true); flatten1($arr); var_export(microtime(true) - $start); echo PHP_EOL."ARRAY_PUSH".PHP_EOL; $arr = initArray(); $start = microtime(true); flatten2($arr); var_export(microtime(true) - $start);

preferences:
40.98 ms | 402 KiB | 5 Q