Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between array_replace and array_merge in PHP

Tags:

arrays

php

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 :

  1. If the arrays contain numeric keys, the later value will not overwrite the original value in array_merge(), which will be done in array_replace().
  2. In 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?

like image 464
Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ Avatar asked Dec 19 '15 05:12

Tᴀʀᴇǫ Mᴀʜᴍᴏᴏᴅ


2 Answers

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
)*/
like image 117
zpr Avatar answered Oct 14 '22 13:10

zpr


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.

Graphic showing the difference

like image 34
Will Avatar answered Oct 14 '22 12:10

Will