0
0

More than 1 year has passed since last update.

アロー演算子で動的に要素を指定する方法

Last updated at Posted at 2022-01-02

※自分用のメモ

問題

PHPを使っていると->(アロー演算子)を使うことがあります。
使い方としては連想配列の要素を指定したり、Laravelのコレクションで使うことがあり

$fruits = ['apple'=>'りんご', 'peach'=>'もも', 'pear'=>'なし'];
$select = $fruits->peach;
print($select);   //もも

↑ざっくりですが、こんな感じで連想配列の要素を指定してやると、その要素を取得してきます。
ただ、このアロー演算子、使っていると指定する要素を動的に変更してやりたいと思うときがあり、その場合は以下のように記載します。

やり方


$animals = ['animal_1' => 'らいおん','animal_2' => 'さる','animal_3' => 'しまうま'];
for ($i = 1; $i <= 3; $i++) {
  $select = $animals->{'animal_' . $i};
  print($select);   
}
  /*
  らいおん
 さる
 しまうま
  */

もしくは

$animals = ['animal_1' => 'らいおん','animal_2' => 'さる','animal_3' => 'しまうま'];
for ($i = 1; $i <= 3; $i++) {
    $prop = 'animal_' . $i;
    $select = $animals->$prop;
    print($select);
}
   /*
    らいおん
   さる
   しまうま
    */

という風に書いてやるとanimal_1からanimal_3までの要素を動的に取得してきます。
知っている人からすると基本的なことですが、教わるまで地味にわからなかったのでメモ代わりに残します。

0
0
1

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