Combine two arrays
The new way of doing it with php7.4 is Spread operator [...]
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
var_dump($fruits);
Spread operator should have better performance than array_merge
A significant advantage of Spread operator is that it supports any traversable objects, while the array_merge function only supports arrays.
This works:
$output = $array1 + $array2;
You should take to consideration that $array1 + $array2 != $array2 + $array1
$array1 = array(
'11' => 'x1',
'22' => 'x1'
);
$array2 = array(
'22' => 'x2',
'33' => 'x2'
);
with $array1 + $array2
$array1 + $array2 = array(
'11' => 'x1',
'22' => 'x1',
'33' => 'x2'
);
and with $array2 + $array1
$array2 + $array1 = array(
'11' => 'x1',
'22' => 'x2',
'33' => 'x2'
);
Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44'
in your example) one key will overwrite preceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in: http://php.net/manual/en/function.array-merge.php