Home > Backend Development > PHP Tutorial > PHP Switch 语句之学习笔记_PHP

PHP Switch 语句之学习笔记_PHP

WBOY
Release: 2016-06-01 11:58:58
Original
1103 people have browsed it

PHP 中的 Switch 语句用于执行基于多个不同条件的不同动作。

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;
}


实例

工作原理:

对表达式(通常是变量)进行一次计算
把表达式的值与结构中 case 的值进行比较
如果存在匹配,则执行与 case 关联的代码
代码执行后,break 语句阻止代码跳入下一个 case 中继续执行
如果没有 case 为真,则使用 default 语句

复制代码 代码如下:
switch ($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";
}
?>

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