博客列表 >多分支结构与switch,循环方式遍历数组,while,for-php14章7.6

多分支结构与switch,循环方式遍历数组,while,for-php14章7.6

希望
希望原创
2020年07月07日 18:53:57750浏览

一.多分支结构与switch

  1. 单分支模板语法,用:开头,关键字结束
    1. $amount = 1000;
    2. $payment = $amount;
    3. if ($amount >= 500) :
    4. $payment = $amount * 0.9;
    5. endif;
    6. echo '实际支付:', $payment, '<br>';
  2. 双分支:if,else,endif
    1. $amount = 400;
    2. if ($amount >= 500) :
    3. $payment = $amount * 0.9;
    4. else :
    5. $payment = $amount;
    6. endif;
    7. echo '实际支付:', $payment, '<br>';
  3. 多分支:if,elseif,else,endif
    1. $amount = 3000;
    2. if ($amount >= 1000 && $amount < 1500) :
    3. $payment = $amount * 0.9;
    4. elseif ($amount >= 1500 && $amount < 2000) :
    5. $payment = $amount * 0.8;
    6. elseif ($amount >= 2500) :
    7. $payment = $amount * 0.7;
    8. else :
    9. $payment = $amount;
    10. endif;
    11. echo '实际支付:', $payment, '<br>';
  4. switch用来简化分支:switch,case,break,default
    1. $amount = 500;
    2. switch (true) {
    3. case $amount >= 1000 && $amount < 1500:
    4. $payment = $amount * 0.9;
    5. break;
    6. case $amount >= 1500 && $amount < 2000:
    7. $payment = $amount * 0.8;
    8. break;
    9. case $amount >= 2500:
    10. $payment = $amount * 0.7;
    11. break;
    12. default:
    13. $payment = $amount;
    14. }
    15. echo '实际支付:', $payment, '<br>';
  • 4.2.switch通常用在单值判断中
    1. $discount = 0.8;
    2. $amount = 3300;
    3. switch ($discount):
    4. case 0.7:
    5. $payment = $amount * 0.7;
    6. break;
    7. case 0.8:
    8. $payment = $amount * 0.8;
    9. break;
    10. case 0.9:
    11. $payment = $amount * 0.9;
    12. break;
    13. default:
    14. $payment = $amount;
    15. endswitch;
    16. echo '实际支付:', $payment, '<br>';

    二.多种循环方式来遍历数组,while,for

    1.while条件判断型循环,入口判断
  • 条件是真就执行循环
    1. $cities = ['北京', '深圳', '广州', '天津', '上海'];
    2. while ($city = current($cities)) {
    3. echo $city, '<br>';
    4. next($cities);
    5. }
  • 怎么才能再次循环,必须指针复位

    1. reset($cities);
    2. while ($city = current($cities)) :
    3. echo $city, '<br>';
    4. next($cities);
    5. endwhile;

    2.判断型循环,出口判断型 do (…) while(条件)

  • do - while 没有模板语法,此时第一个北京不见了
    1. do {
    2. echo $city, '<br>';
    3. next($cities);
    4. } while ($city = current($cities));
    3.计数型循环:for(循环变量初始化,循环条件,更新循环条件){…}
  1. for ($i = 0; $i < count($cities); $i++) {
  2. echo $cities[$i], '<br>';
  3. }
  4. echo '<hr>';
  5. for ($i = 0; $i < count($cities); $i++) :
  6. echo $cities[$i], '<br>';
  7. endfor;
  • 如果把第三个广州不要,广州值是2,输出拦截,后面的就终止不输出了
    1. for ($i = 0; $i < count($cities); $i++) :
    2. if ($i > 1) break;
    3. echo $cities[$i], '<br>';
    4. endfor;
  • 选择性输出,跳过一些值广州
    1. for ($i = 0; $i < count($cities); $i++) :
    2. if ($i === 2) continue;
    3. echo $cities[$i], '<br>';
    4. endfor;
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议