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.

配列から指定したデータを直接変数に代入する

Last updated at Posted at 2022-06-29

TypeScriptで分割代入が日常的に使われてるのでPHPでもできるのか調べてたらありました。
PHPで見かけたことがないのでマイナーっぽいです。

まずは標準的なやり方。

$array = [1, 2, 3];
$a = $array[0];
$b = $array[1];
$c = $array[2];

リスト構文を使うやり方。

[$a, $b, $c] = [1, 2, 3];

//$a 1
//$b 2
//$c 3

順不同でよくなるため、連想配列の方が安全に割り当て可能。

["a" => $a,"b" => $b,"c" => $c] = ["a" => 1,"b" => 2,"c" => 3];

//$a 1
//$b 2
//$c 3

compact関数を組み合わせてキーを振った連想配列を組み立ててから使うと便利。

配列の組み立て
$a = 1;
$b = 2;
$c = 3;

$array = compact("a", "b", "c");
値の展開
["a" => $a,"b" => $b,"c" => $c] = $array;

//$a 1
//$b 2
//$c 3

結論

わりと好みな気がしなくもない・・・。

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?