0
0

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 1 year has passed since last update.

PHP:二つの配列を結合する方法大きく二つ。基本はarray_merge使用だがいくつか注意点ある

Last updated at Posted at 2023-02-17

+ の場合:左辺の要素数よりも右辺の要素数が多ければ、その多い要素だけを左辺の要素の後ろに結合

$arrA1 = ['a', 'b'];
$arrA2 = ['c', 'd', 'e'];
$arrA = $arrA1 + $arrA2;
var_export($arrA);
echo PHP_EOL;
// $arrA は  ['a', 'b', 'c', 'e'] が入っている。

array_merge の場合:「文字列ならば」想像通り順序よく結合してくれる

$arrB1 = ['a', 'b', 'c'];
$arrB2 = ['d', 'e'];
$arrB = array_merge($arrB1, $arrB2);
echo PHP_EOL;
var_export($arrB);
// $arrB は ['a', 'b', 'c', 'd', 'e'] が入っている。

しかし、array_merge はキーが数字の場合、キーが破棄される

# array_mergeの注意点
$arrC1 = ['1' => 'a'];
$arrC2 = ['10' => 'b'];
$arrC = $arrC1 + $arrC2;
var_dump($arrC); // キーが数字でもキーとして保持して正常に動作する

$arrD1 = ['1' => 'a'];
$arrD2 = ['10' => 'b'];
$arrD = array_merge($arrD1, $arrD2);
var_dump($arrD); // array_mergeの場合、キーが数字だと破棄されてキーが0から割り振られてしまう。
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?