テストコード
test.php
<?php
$a = array(
'a' => 'apple',
'b' => 'bear',
'c' => 'coffee',
);
$b = array(
'a' => 'ant',
'b' => 'bug',
'd' => 'deep',
);
echo "\$a + \$b\n";
$c = $a + $b;
print_r($c);
echo "array_merge(\$a, \$b)\n";
$c = array_merge($a, $b);
print_r($c);
echo "\$b + \$a\n";
$c = $b + $a;
print_r($c);
echo "array_merge(\$b, \$a)\n";
$c = array_merge($b, $a);
print_r($c);
結果
result
$a + $b
Array
(
[a] => apple
[b] => bear
[c] => coffee
[d] => deep
)
array_merge($a, $b)
Array
(
[a] => ant
[b] => bug
[c] => coffee
[d] => deep
)
$b + $a
Array
(
[a] => ant
[b] => bug
[d] => deep
[c] => coffee
)
array_merge($b, $a)
Array
(
[a] => apple
[b] => bear
[d] => deep
[c] => coffee
)
まとめ
+ 演算子は、同一キーに対し、上書きしない。
array_merge は同一キーに対し、上書きする。