I am trying to figure out the differences between array_replace() and array_merge(). The question actually came to my mind after this post : PHP array_merge empty values always less prioritar, where the problem actually can be solved with any of these two functions. So, I was trying to find out in which cases we should use array_replace instead of array_merge and vice versa.
After reading the php documentation for both functions, I find these two differences :
array_merge()
, which will be done in array_replace()
.array_merge()
, values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array, which shouldn't happen with array_replace()
.Since the differences are only related to numeric keys, can we safely say that, functions array_replace()
and array_merge()
are exactly equivalent when we are dealing with associative arrays? Or is there any other difference which I am missing?
For arrays with string keys, yes these are equivalent, as you mentioned. If you have numeric keys, array_merge()
will append them as required, and even re-order them if necessary, whereas array_replace()
will overwrite the original values.
For example,
$a = array('a' => 'hello', 'b' => 'world');
$b = array('a' => 'person', 'b' => 'thing', 'c'=>'other', '15'=>'x');
print_r(array_merge($a, $b));
/*Array
(
[a] => person
[b] => thing
[c] => other
[0] => x
)*/
print_r(array_replace($a, $b));
/*Array
(
[a] => person
[b] => thing
[c] => other
[15] => x
)*/
As you can see, array_merge
has re-indexed the numeric keys of the array, and both of them simply update string keys.
However, when you have numeric keys, array_merge()
will simply not care about keys, and add everything in the order it sees, deleting nothing, whereas array_replace()
will, as the name suggests, replace keys with similar (numeric) indices:
<?php
$a = array('0'=>'a', '1'=>'c');
$b = array('0'=>'b');
print_r(array_merge($a, $b));
/*Array
(
[0] => a
[1] => c
[2] => b
)*/
print_r(array_replace($a, $b));
/*Array
(
[0] => b
[1] => c
)*/
Jarek gave a nice explanation in his article here:
https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/
He also adds in the use of the + operator with arrays for comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With