What is the difference between the union of an array via soma operator and the array_merge function?

Asked

Viewed 433 times

6

To join two arrays in a new array in PHP, we can do through the function array_merge 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 uniting the arrays?

2 answers

7


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

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

  • In the merger, the values of the text keys existing in $b shall prevail over the values in $a, if the same key exists in the two arrays. Already in the union, the key values in $a.

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

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
)

http://ideone.com/mx7OOB

  • I’m still confused by these two ways...

  • 1

    It’s because they’re really confusing :)

  • Sorry, I forgot to mark it with "greenie"

5

In the array_merge, the same keys are changed; with the operator +, they stay intact.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.