What is the difference between joining an array via sum operator and the array_merge function?

5

To join two arrays in a new array in PHP, we can do it through the array_merge function or through the sum operator ( + ).

In this case we have two examples:

$a = ['stack' => 'overflow'];
$b = ['oveflow' => 'stack'];

$c = array_merge($a, $b); //

$d = $a + $b;


print_r($c); // Array ( [stack] => overflow [oveflow] => stack )

print_r($d); // Array ( [stack] => overflow [oveflow] => stack )

What are the main differences between these two ways of joining arrays ?

    
asked by anonymous 27.02.2015 / 14:24

2 answers

6

Considering the arrays $a and $b , the differences in the result of array_merge($a, $b) (fusion) and $a + $b (union) will be:

  • In the merge, the values of the numeric keys in both will be kept in the result (however with keys reindexed). In the union, the result retains the value that is in $a , and the value in $b is discarded.

  • In the merge, the values of the existing text keys in $b prevail over the values in $a , if the same key exists in both arrays. In the union, the values of the keys in $a prevail.

  • In both operations, numeric keys existing only in $b are included in the result, reindexed when needed.

Example ( "borrowed" from SOen ):

$ar1 = [
   0  => '1-0',
  'a' => '1-a',
  'b' => '1-b'
];

$ar2 = [
   0  => '2-0',
   1  => '2-1',
  'b' => '2-b',
  'c' => '2-c'
];

print_r(array_merge($ar1,$ar2));
print_r($ar1+$ar2);
Array
(
    [0] => 1-0
    [a] => 1-a
    [b] => 2-b
    [1] => 2-0
    [2] => 2-1
    [c] => 2-c
)
Array
(
    [0] => 1-0
    [a] => 1-a
    [b] => 1-b
    [1] => 2-1
    [c] => 2-c
)

link

    
27.02.2015 / 14:47
4

In% with%, equal keys are changed; with the array_merge operator, they remain intact.

In the example documentation , the + of an empty array and another with array_merge returns an array with 1 => "data" , but using the same arrays with the 0 => "data" operator, the result is an array with + .

    
27.02.2015 / 14:37