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 5 years have passed since last update.

foreachをlistを使ってかっこよく取得する

Last updated at Posted at 2020-06-22

よく使う使い方

$fruitList = [
 '1'  => 'リンゴ',
 '2'  => 'レモン',
 '3'  => 'バナナ'
];

foreach($fruitList as $index => $name){
 dd($index. ':'. $name);
}
Screenshot_1.png

1:リンゴと出力されました。

一般的な使い方として、$key => $valueの形で使用します。

これが例えば、$valueのほうが配列になった場合を考えてみましょう。

valueが配列の場合

添字配列の場合

$fruitInfoList = [
 '1'  => ['リンゴ', '100円'],
 '2'  => ['レモン', '200円'],
 '3'  => ['バナナ', '300円']
];

foreach($fruitInfoList as $index => $fruitInfo){
 dd($index. ':'. $fruitInfo[0]. ':'. $fruitInfo[1]);
}
Screenshot_2.png

これでは、0と1という添字を書いて、取得するのはちょっとみにくいですね。
連想配列にしてみます。

連想配列の場合

$fruitInfoList = [
 '1'  => [
    'name'  => 'リンゴ',
    'price' => '100円'
 ],
 '2'  => [
    'name'  => 'レモン',
    'price' => '200円'
 ],
 '3'  => [
    'name'  => 'バナナ',
    'price' => '300円'
 ],
];

foreach($fruitInfoList as $index => $fruitInfo){
 dd($index. ':'. $fruitInfo['name']. ':'. $fruitInfo['price']);
}
Screenshot_2.png

取得の際は、nameとpriceと意味付けができて見やすくなりましたが、宣言する際が少し大変で、長いし冗長ですね。
list関数を使ってみましょう。

listを使用した際

listは、定義された変数の順番に配列の要素が代入されます。さっそく見てみましょう
https://www.sejuku.net/blog/24406

$fruitList = [
 '1'  => ['リンゴ', '100円'],
 '2'  => ['レモン', '200円'],
 '3'  => ['バナナ', '300円'],
];

foreach($fruitList as $index => list($name, $price)){
 dd($index. ':'. $name. ':'. $price);
}
Screenshot_2.png だいぶすっきりしました。 foreachの中で、$fruitInfoと命名していたものが消えました。(変数を命名するのは難しいので、避けられるなら避けたほうが良いときもある)
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?