57
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[PHP] 配列に対する +演算子 と array_merge の比較 (小ネタ)

Posted at

テストコード

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 は同一キーに対し、上書きする。

参考

配列演算子
array_merge

57
48
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?