0
1

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と+演算子の比較

Last updated at Posted at 2018-10-31

array_mergeと+演算子の違いを忘れないためのメモ

使用する配列

$array_1 = [
    'a'   => '1-A',
    'b_1' => '1-B1',
    'c'   => [
        'c_1' => '1-C1',
        'c_2' => '1-C2',
    ],
    'd'   => [
        'd_1' => '1-D1',
        'd_2' => '1-D2',
    ],
];

$array_2 = [
    'a'   => '2-A',
    'b_2' => '2-B2',
    'c'   => [
        'c_1' => '2-C1',
        'c_2' => '2-C2',
    ],
    'd'   => [
        'd_1'   => '2-D1',
        'd_2_2' => '2-D22',
    ],
];

それぞれの処理

var_dump('テスト1:array_merge');
var_dump(array_merge($array_1, $array_2));

var_dump('テスト2:+演算子');
var_dump($array_1 + $array_2);

結果

string(27) "テスト1:array_merge"
array(5) {
  ["a"]=>
  string(3) "2-A"
  ["b_1"]=>
  string(4) "1-B1"
  ["c"]=>
  array(2) {
    ["c_1"]=>
    string(4) "2-C1"
    ["c_2"]=>
    string(4) "2-C2"
  }
  ["d"]=>
  array(2) {
    ["d_1"]=>
    string(4) "2-D1"
    ["d_2_2"]=>
    string(5) "2-D22"
  }
  ["b_2"]=>
  string(4) "2-B2"
}
string(26) "テスト2:+演算子"
array(5) {
  ["a"]=>
  string(3) "1-A"
  ["b_1"]=>
  string(4) "1-B1"
  ["c"]=>
  array(2) {
    ["c_1"]=>
    string(4) "1-C1"
    ["c_2"]=>
    string(4) "1-C2"
  }
  ["d"]=>
  array(2) {
    ["d_1"]=>
    string(4) "1-D1"
    ["d_2"]=>
    string(4) "1-D2"
  }
  ["b_2"]=>
  string(4) "2-B2"
}

まとめ

array_merge

  • キーが同じ場合、後の引数の配列で上書き
  • 多次元配列であろうが、第1階層の引数のみで比較

+演算子

  • キーが同じ場合は、先の引数が優先(上書きされない。)
  • こちらも、第1階層のみ比較

※第2階層以降も比較したい場合は、別の処理が必要。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?