71
63

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の配列結合

Posted at

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"
}
*/

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

71
63
2

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
71
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?