If you wrote some PHP, most likely you have used array_merge
here and there for your arrays. You may have met array_replace
function, introduced in PHP5.3. Finally, you could notice +
operator (aka union).
Since all 3 do similar thing, and the docs don’t quite describe the difference between them, here’s a nice image of it
There are a few things to consider:
array_merge
andarray_replace
work just the same for keyed (associative) elements, so they can be used interchangeably:
1234// associative arraysarray_replace($a, $b) === array_merge($a, $b)
array_replace
and+
do the opposite always:
1234567// numeric arraysarray_replace($a, $b) === $b + $a// associative arraysarray_replace($a, $b) == $b + $a // equal, but not identical ===array_merge
behaves differently to the other 2 with numeric arrays:
1234// numeric arraysarray_replace($a, $b) != array_merge($a, $b)
That being said, we could think of the +
operator as kinda redundant, since the same can be achieved with array_replace
function.
However, there are cases, where it comes in handy: say you have an $options
array being passed to a function/method, and there are also defaults to be used as fallback:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// we could do it like this function foo(array $options) { $defaults = ['foo' => 'bar']; $options = array_replace($defaults, $options); // ... } // but + here might be way better: function foo(array $options) { $options += ['foo' => 'bar']; // ... } |