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?

【PHP】スプレッド構文で配列結合

Last updated at Posted at 2024-10-06

PHP7.4からスプレッド構文が使用可能になりました。

$array1 = ['apple', 'banana', 'peach'];
$result = ['melon', ...$array1];

// 出力結果
Array
(
    [0] => melon
    [1] => apple
    [2] => banana
    [3] => peach
)

さらにPHP8.1から、キー名に文字列が含まれている連想配列にも対応できるようになりました。

$array1 = ['red' => 'apple', 'yellow' => 'banana', 'pink' => 'peach'];
$result = [...['green' => 'melon'], ...$array1];

// 出力結果
Array
(
    [green] => melon
    [red] => apple
    [yellow] => banana
    [pink] => peach
)

同じ実行結果として、PHP組み込み関数のarray_mergeを使う選択肢はありますが、
個人的にはスプレッド構文の方が見やすい、、

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?