3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array1 = [ 'fruits' => [ 'apple' => 'red', 'banana' => 'yellow' ], 'numbers' => [1, 2] ]; $array2 = [ 'fruits' => [ 'orange' => 'orange', 'apple' => 'green' // Should overwrite 'red' ], ]; $array3 = [ 'numbers' => [2, 3, 4], // Should extend, not replace 'colors' => ['blue', 'purple'] // New key should be added ]; function mergeNestedArraysInefficient(array $array, array ...$otherArrays) { foreach ($otherArrays as $other) { if (array_is_list($other)) { $array = array_values(array_unique(array_merge($array, $other))); continue; } foreach ($other as $k => $v) { if (is_array($v) && key_exists($k, $array)) { $array[$k] = mergeNestedArraysInefficient($array[$k], $v); } else { $array[$k] = $v; } } } return $array; } var_export(mergeNestedArraysInefficient($array1, $array2, $array3));

preferences:
22.18 ms | 409 KiB | 5 Q