Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
63
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@ukisoft

PHPの配列結合

PHPの配列結合には、array_merge()、array_merge_recursive()、+演算子があるのですが、少しずつ結果が異なります。
具体的には、keyが数字の場合、array_merge()とarray_merge_recursive()は、keyを振りなおして結合。
+演算子は、keyそのままで、前の配列の値を残します。

$arrayFirst = [0 => 'a', 10 => 'b'];
$arraySecond = [0 => 'A', 100 => 'B'];
var_dump(array_merge($arrayFirst, $arraySecond));
var_dump(array_merge_recursive($arrayFirst, $arraySecond));
var_dump($arrayFirst + $arraySecond);

/* 結果
array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "A"
  [3]=>
  string(1) "B"
}
array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "A"
  [3]=>
  string(1) "B"
}
array(3) {
  [0]=>
  string(1) "a"
  [10]=>
  string(1) "b"
  [100]=>
  string(1) "B"
}
*/

ところが、keyが文字列だった場合、array_merge()は後ろの配列の値を残し、array_merge_recursive()の場合は、新たに配列を作り、両方残すように処理が変わります(+演算子は変化なし)。

$arrayThird = ['zero' => 'a', 'ten' => 'b'];
$arrayFourth = ['zero' => 'A', 'hundred' => 'B'];
var_dump(array_merge($arrayThird, $arrayFourth));
var_dump(array_merge_recursive($arrayThird, $arrayFourth));
var_dump($arrayThird + $arrayFourth);

/* 結果
array(3) {
  ["zero"]=>
  string(1) "A"
  ["ten"]=>
  string(1) "b"
  ["hundred"]=>
  string(1) "B"
}
array(3) {
  ["zero"]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "A"
  }
  ["ten"]=>
  string(1) "b"
  ["hundred"]=>
  string(1) "B"
}
array(3) {
  ["zero"]=>
  string(1) "a"
  ["ten"]=>
  string(1) "b"
  ["hundred"]=>
  string(1) "B"
}
*/

これは正しく使わないと、バグの元になりそうですね・・・。

63
Help us understand the problem. What is going on with this article?
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
63
Help us understand the problem. What is going on with this article?