本文章要讲到了php 两种流程判断语句,有switch语句和if else ,if()语句,下面我们来详细的看看实例吧。
- switch(variable){
- case value1:
- statement1;
- break;
- case value2:
- …
- default:
- defulat statement;
- }
switch语句根据variable的值,依次与case中的value值相比较,如果不相等,继续查找下一个
case;如果相等,就执行对应的语句,直到switch语句结束或者遇见break为止。
- <?php
- switch ($i) {
- case "apple":
- echo "i is apple";
- break;
- case "bar":
- echo "i is bar";
- break;
- case "cake":
- echo "i is cake";
- break;
- }
- ?>
实例二
- <?php
- switch ($i) {
- case 0:
- echo "i equals 0";
- break;
- case 1:
- echo "i equals 1";
- break;
- case 2:
- echo "i equals 2";
- break;
- }
- ?>
实例三
- <?php
- switch ($i) {
- case 0:
- case 1:
- case 2:
- echo "i is less than 3 but not negative";
- break;
- case 3:
- echo "i is 3";
- }
- ?>
if…else语句只能选择两种结果:要么执行真,要么执行假。但现在有2种以上的选择该怎么办呢?这时,可以使用esleif(也可以写作else if)语句来执行,该语法格式为:
- if(expression1){
- statement1;
- }else if(expression2){
- statement2;
- }
- …
- else{
- statementn;
- }
实例
- <?php
- $moth = date(“n”);
- $today = date(“j”);
- if($today >= 1and $today <= 10){
- echo’今天是’.$moth.’月’.$today.’日上旬’;
- }elseif ($today >10 and $today <=20){
- echo’今天是’.$moth.’月’.$today.’日中旬’;
- }else{
- echo’今天是’.$moth.’月’.$today.’日下旬’;
- }
- ?>
如果当前日期是周五,下面的例子会输出 "Have a nice weekend!",如果是周日,则输出 "Have a nice Sunday!",否则输出 "Have a nice day!":
- <html>
- <body>
- <?php
- $d=date("D");
- if ($d=="Fri")
- echo "Have a nice weekend!";
- elseif ($d=="Sun")
- echo "Have a nice Sunday!";
- else
- echo "Have a nice day!";
- ?>
- </body>
- </html>
新闻热点
疑难解答