- array_push: documentation ( source)
- microtime: documentation ( source)
- var_export: documentation ( source)
- array_values: documentation ( source)
<?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);