php switch语句多个值匹配同一代码块应用示例_PHP

WBOY
Release: 2016-06-01 11:50:37
Original
1036 people have browsed it

先说说switch()语句的格式

switch(表达式){

case 匹配1:

当匹配1和表达式匹配成功执行的代码;

break;

case 匹配2:

当匹配2和表达式匹配成功执行的代码;

break;

default:

如果case语句没有与表达式成功所执行的代码;

}

理解 switch 是怎样执行的非常重要。switch 语句一行接一行地执行(实际上是语句接语句)。开始时没有代码被执行。仅当一个 case 语句中的值和 switch 表达式的值匹配时 PHP 才开始执行语句,直到 switch 的程序段结束或者遇到第一个 break 语句为止。如果不在 case 的语句段最后写上 break 的话,PHP 将继续执行下一个 case 中的语句段。

例子:

<&#63;php

switch($i){

case 1:

echo "$i的值是1";

break;

case 2:

echo "$i的值是2";

break;

case 3:

echo "$i的值是3";

break;

default:

echo "$i的值不是1、2、3";

}

&#63;>
Copy after login

在一个 case 中的语句也可以为空,这样只不过将控制转移到了下一个 case 中的语句,知道下一个case的语句块不为空,这样就实现了多个值匹配同意代码块:

当$i的值为1或2或3时输出同一语句:

<&#63;php

switch($i){

case 1:

case 2:

case 3:

echo "$i的值为$i的值为1或2或3";

break;

}
&#63;>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!