iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 11
0

流程控制結構

  • 循序:由上而下
  • 選擇:條件判斷
  • 重複:迴圈控制

if:單一條件判斷

範例:體重60,理想體重50,當體重大於理想體重印出You should go on a diet !

<?php 
    $weight = 60;
    $ideal_weight = 50;
    if($weight > $ideal_weight){
        echo "You should go on a diet !";
    }  
?>

輸出:
You should go on a diet !

if-else:二選一條件

範例:體重40,理想體重50,當體重大於理想體重印出You should go on a diet !否則印出You should eat more !

<?php 
    $weight = 40;
    $ideal_weight = 50;
    if($weight > $ideal_weight){
        echo "You should go on a diet !";
    }else{
        echo "You should eat more!";
    }
?>

輸出:
You should eat more!

if-elseif:多個選擇

範例:BMI檢測,大於24印出Overweight ! ,小於18.5印出Too Skin !,介於之間印出Ideal Weight ! 當BMI=25時。

<?php 
    $bmi = 25;
    $bmi_min = 18.5;
    $bmi_max = 24;
    if($bmi>$bmi_max){
        echo "Overweight!";
    }elseif($bmi>=$bmi_min && $bmi<=$bmi_max){
        echo "Ideal Weight!";
    }elseif($bmi<$bmi_min){
        echo "Too Skin!";
    }
?>

輸出:
Overweight!

switch:多個選擇

範例:依照數字印出所對應的星期英文字,當$day=2時。記得在後方加入break;才能跳出不繼續執行程式

<?php 
   $day = 2;
   switch($day){
       case 1:
        echo "Monday";
        break;
       case 2:
        echo "Tuesday";
        break;
       case 3:
        echo "Wednesday";
        break;
       case 4:
        echo "Thursday";
        break;
       case 5:
        echo "Friday";
        break;
       case 6:
        echo "Saturday";
        break;
       case 7:
        echo "Sunday";
        break;
   }
?>

輸出:
Tuesday


上一篇
Day10-PHP運算子、運算式(2)
下一篇
Day12-PHP迴圈
系列文
PHP入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言