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...
– Jorge B.
It’s because they’re really confusing :)
– bfavaretto
Sorry, I forgot to mark it with "greenie"
– Wallace Maxters