switch (expression){case label1:code to be executed if expression = label1;break;case label2:code to be executed if expression = label2;break;default:code to be executedif expression is differentfrom both label1 and label2;}
工作原理:
对表达式(通常是变量)进行一次计算
把表达式的值与结构中 case 的值进行比较
如果存在匹配,则执行与 case 关联的代码
代码执行后,break语句阻止代码跳入下一个 case 中继续执行
如果没有 case 为真,则使用 default 语句
下面的例子使用两种不同方法实现同样的事,一个用一系列的 if 语句,另一个用 switch 语句:
1 、switch结构
2、 switch结构可以用字符串
为避免错误,理解 switch 是怎样执行的非常重要。switch 语句一行接一行地执行(实际上是语句接语句)。开始时没有代码被执行。仅当一个 case 语句中的值和 switch 表达式的值匹配时 php 才开始执行语句,直到 switch 的程序段结束或者遇到第一个 break 语句为止。如果不在 case 的语句段最后写上 break 的话,php 将继续执行下一个 case 中的语句段。例如:
This article discusses the efficiency of using char str[] and char *str and whether there is any reason to prefer one over the other. It explains the difference between the two and provides an example to illustrate their usage. ...
[详细]