PHP switch 语句
switch
语句用于基于不同条件执行不同动作。
Switch 语句
如果您希望有选择地执行若干代码块之一,请使用 switch
语句。
使用 switch
语句可以避免冗长的 if..elseif..else 代码块。
语法
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
工作原理:
- 对表达式(通常是变量)进行一次计算
- 把表达式的值与结构中 case 的值进行比较
- 如果存在匹配,则执行与 case 关联的代码
- 代码执行后,
break
语句阻止代码跳入下一个 case 中继续执行 - 如果没有 case 为真,则使用
default
语句
实例
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
亲自试一试 »
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>