1
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.

【PHP7.4 ~ 】スプレッド構文で配列の結合をスマートに

Last updated at Posted at 2023-02-13

概要

JavaScriptにあるスプレッド構文と同じようなものがPHP7.4から使用できるようになってました。

$insects = ["🐛", "🐝"];
$animals = ["🐱", "🐶", "🐇"];
$creatures = [...$insects, ...$animals];
dd($creatures);
結果
array:5 [
  0 => "🐛"
  1 => "🐝"
  2 => "🐱"
  3 => "🐶"
  4 => "🐇"
]
$insects = ["🐛", "🐝"];
$animals = ["🐱", "🐶", "🐇"];
$fishes = ["🐟", "🐠"];
$creatures = [...$insects, ...$animals, ...$fishes];
dd($creatures);
結果
array:7 [
  0 => "🐛"
  1 => "🐝"
  2 => "🐱"
  3 => "🐶"
  4 => "🐇"
  5 => "🐟"
  6 => "🐠"
]

PHP7.4 注意点

文字列がキーだと結合出来ません。

$insects = ["ようちゅう" => "🐛", "はち" => "🐝"];
$fishes = ["さかな1" => "🐟", "さかな2" => "🐠"];
$creatures = [...$insects, ...$fishes];
dd($creatures);
Error
Cannot unpack array with string keys

しかしPHP8.1から

文字列のキーも対応し、array_mergeで実現出来る事はスプレッド構文でも実現出来るようになりました。

追記

php5系からでも関数の引数に渡したり受け取る時には使えたみたいです。

参考

1
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
1
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?