php 流程控制语句

本文章要讲到了php 两种流程判断语句,有switch语句和if else ,if()语句,下面我们来详细的看看实例吧。

  1. switch(variable){
  2. case value1:
  3. statement1;
  4. break;
  5. case value2:
  6. default:
  7. defulat statement;
  8. }

switch语句根据variable的值,依次与case中的value值相比较,如果不相等,继续查找下一个

case;如果相等,就执行对应的语句,直到switch语句结束或者遇见break为止。

  1. <?php
  2. switch ($i) {
  3. case "apple":
  4. echo "i is apple";
  5. break;
  6. case "bar":
  7. echo "i is bar";
  8. break;
  9. case "cake":
  10. echo "i is cake";
  11. break;
  12. }
  13. ?>

实例二

  1. <?php
  2. switch ($i) {
  3. case 0:
  4. echo "i equals 0";
  5. break;
  6. case 1:
  7. echo "i equals 1";
  8. break;
  9. case 2:
  10. echo "i equals 2";
  11. break;
  12. }
  13. ?>

实例三

  1. <?php
  2. switch ($i) {
  3. case 0:
  4. case 1:
  5. case 2:
  6. echo "i is less than 3 but not negative";
  7. break;
  8. case 3:
  9. echo "i is 3";
  10. }
  11. ?>

if…else语句只能选择两种结果:要么执行真,要么执行假。但现在有2种以上的选择该怎么办呢?这时,可以使用esleif(也可以写作else if)语句来执行,该语法格式为:

  1. if(expression1){
  2. statement1;
  3. }else if(expression2){
  4. statement2;
  5. }
  6. else{
  7. statementn;
  8. }

实例

  1. <?php
  2. $moth = date(“n”);
  3. $today = date(“j”);
  4. if($today >= 1and $today <= 10){
  5. echo’今天是’.$moth.’月’.$today.’日上旬’;
  6. }elseif ($today >10 and $today <=20){
  7. echo’今天是’.$moth.’月’.$today.’日中旬’;
  8. }else{
  9. echo’今天是’.$moth.’月’.$today.’日下旬’;
  10. }
  11. ?>

如果当前日期是周五,下面的例子会输出 "Have a nice weekend!",如果是周日,则输出 "Have a nice Sunday!",否则输出 "Have a nice day!":

  1. <html>
  2. <body>
  3. <?php
  4. $d=date("D");
  5. if ($d=="Fri")
  6. echo "Have a nice weekend!";
  7. elseif ($d=="Sun")
  8. echo "Have a nice Sunday!";
  9. else
  10. echo "Have a nice day!";
  11. ?>
  12. </body>
  13. </html>