Home > php教程 > php手册 > PHP控制语句之Switch

PHP控制语句之Switch

WBOY
Release: 2016-06-13 11:01:49
Original
1367 people have browsed it

Switch 语句

如果您希望有选择地执行若干代码块之一,请使用 Switch 语句。

使用 Switch 语句可以避免冗长的 if..elseif..else 代码块。

语法

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 executed  if expression is different   from both label1 and label2;}
Copy after login

实例

工作原理:

对表达式(通常是变量)进行一次计算

把表达式的值与结构中 case 的值进行比较

如果存在匹配,则执行与 case 关联的代码

代码执行后,break 语句阻止代码跳入下一个 case 中继续执行

如果没有 case 为真,则使用 default 语句

<?phpswitch ($x){case 1:  echo "Number 1";  break;case 2:  echo "Number 2";  break;case 3:  echo "Number 3";  break;default:  echo "No number between 1 and 3";}?>
Copy after login


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template