Help us understand the problem. What is going on with this article?

配列結合について

More than 1 year has passed since last update.

配列結合

array_merge()関数

引数に複数の配列を指定した場合、前の配列に後ろの配列を追加した配列を返す。
数値添字の配列を結合する際に、添字が重複した場合、値は上書きしない
(※ただし連想配列の場合は後ろの配列の値で上書きされる)

array_merge_recursive()関数

数値添字の配列を結合する場合、array_merge()関数と同じ結果だが、連想配列の結合を行う際に、重複していた場合は配列のネストを①段深くして値を残す

+演算子

配列は+演算子でも結合できるらしい
数値添字配列、連想配列にかかわらず、添字が重複した場合は、前の配列の値を優先して結合を行う

サンプル

$data1 = ['a']
$data2 = ['A',100=>'B'];

//array_merge() の場合
print_r(array_merge($data1,$data2));
Array
(
  [0]=>a
  [1]=>A
  [2]=>B
)


//array_merge_recursive() の場合
print_r(array_merge_recursive($data1,$data2));
(
  [0]=>a
  [1]=>A
  [2]=>B
)

//演算子で結合した場合
//後ろの配列が優先される
print_r($data1 + $data2);
(
  [0]=>a
  [100]=>B
)


//連想配列結合の場合
//後半の配列が優先される
$data3 = ['a'=>1];
$data4 = ['a'=>'A','b'=>'B'];

//array_merge_recursive() の場合
print_r(array_merge_recursive($data3,$data4));

Array
(
  [a]=>A
  [b]=>B
)


//array_merge_recursive() の場合
//上書きされず、ネスト化される
print_r(array_merge_recursive($data3,$data4));

Array
(
  [a]=>Array
  (
     [0] => 1
     [1] => A
  )
  [b]=>B  
)

//演算子で結合した場合
//前半の配列が上書きされる
print_r($data3 + $data4);
(
  [a]=>1
  [b]=>B
)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした