Differences between array_replace and array_merge in PHP
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)); print_r(array_replace($a, $b));
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:
$a = array('0'=>'a', '1'=>'c');
$b = array('0'=>'b'); print_r(array_merge($a, $b)); print_r(array_replace($a, $b));