LoginSignup
1
0

More than 5 years have passed since last update.

【備忘録】Progate PHP 道場コースⅠ まとめ

Posted at

Progateで学習中のPHPについて、すぐにコードを見直せるように『PHP 道場コースⅠ』の11問目をメモしています。

answer.php
CURRYは900円です
PASTAは1200円です
COFFEEは600円です
合計金額は2700円です
PASTAが最高価格で1200円です
index.php
<?php
$menus = array(
  array('name' => 'CURRY', 'price' => 900),
  array('name' => 'PASTA', 'price' => 1200),
  array('name' => 'COFFEE', 'price' => 600)
);

// この下にコードを書いてください
$totalPrice = 0;
$maxPrice =0;
$maxPriceName = '';
foreach ($menus as $menu){
  echo $menu['name'].'は'.$menu['price'].'円です'.'<br>';
  $totalPrice += $menu['price'];
  if ($menu['price'] > $maxPrice){
    $maxPrice = $menu['price'];
    $maxPriceName = $menu['name'];
  } 
}
echo '合計金額は'.$totalPrice.'円です'.'<br>';
echo $maxPriceName.'が最高価格で'.$maxPrice.'円です';

上が問題と正答です。

下が解説です。

setting.php
$totalPrice = 0;
//数字を一つずつ足していくためにまず元となる変数を設定する。
$maxPrice = 0;
//数字を二つ並べて比較し、大きい方と入れ替えるために、最初の数字を仮に設定する。
$maxPriceName = '';
//$maxPriceのメニュー名を入れるための変数を設定する。
```。

```totalPrice.php
$totalPrice += $menu['price'];
//ループのvalue要素を一つずつ取得し足していく。
maxPrice.php
if ($menu['price'] > $maxPrice){
    $maxPrice = $menu['price'];
    $maxPriceName = $menu['name'];
  } 
//ループ処理の中で$maxPriceよりも大きい['price']が現れたとき、$amxPriceにその['price']を代入(上書き)する。
//同時に['price']を持っているkey要素の名前を上書きする。
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