15
16

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.

配列の結合

Last updated at Posted at 2014-10-26

mpyw様からのご教示を受けて配列の結合に関して誤った認識をしていたため、改めて動作を確認してみました。
配列の結合を行う際、大きく分けて方法は2つあります。
(細かくいうとarray関数による方法はもっとあります)

  • array_merge()
  • +(プラス)演算子

ただしその挙動を正しく理解していないと、思わなぬ不具合を招きます。

array_merge()の場合

<?php
$x = array(
    0 => 'x-0',
    1 => 'x-1',
    2 => 'x-2',
    'a' => 'x-a',
    'b' => 'x-b',
    'c' => 'x-c',
);
$y = array(
    0 => 'y-0',
    1 => 'y-1',
    2 => 'y-2',
    'a' => 'y-a',
    'b' => 'y-b',
    'c' => 'y-c',
);
print_r(array_merge($x, $y));
Array
(
    [0] => x-0
    [1] => x-1
    [2] => x-2
    [a] => y-a
    [b] => y-b
    [c] => y-c
    [3] => y-0
    [4] => y-1
    [5] => y-2
)

+(プラス演算子)の場合

<?php
$x = array(
    0 => 'x-0',
    1 => 'x-1',
    2 => 'x-2',
    'a' => 'x-a',
    'b' => 'x-b',
    'c' => 'x-c',
);
$y = array(
    0 => 'y-0',
    1 => 'y-1',
    2 => 'y-2',
    'a' => 'y-a',
    'b' => 'y-b',
    'c' => 'y-c',
);
print_r($x + $y);
Array
(
    [0] => x-0
    [1] => x-1
    [2] => x-2
    [a] => x-a
    [b] => x-b
    [c] => x-c
)

結論

    • 演算子は常に 連想配列 として 前優先 でキーをセットする
  • array_merge 関数は 文字列キーは連想配列 として 後優先 でキーをセットし、 整数キーは通常配列 として 末尾 に新しく要素を追加する
15
16
4

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
15
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?