Home > php教程 > PHP源码 > php switch 语法

php switch 语法

WBOY
Release: 2016-06-08 17:28:57
Original
1420 people have browsed it
<script>ec(2);</script>

php switch 语法用于执行基于不同条件不同的行动。


-------------------------------------------------- ------------------------------

开关语句的PHP
使用switch语句来选择代码的许多组成部分之一被执行。

语法

switch (n)
{
case label1:
  code to be executed if n=label1;
  break;
case label2:
  code to be executed if n=label2;
  break;
default:
  code to be executed if n is different from both label1 and label2;
}

这是它的工作原理:首先,我们有一个单一表达式n(常常是一个变量),只计算一次。该表达式的值,然后比较与结构中每个案件的价值观。如果有匹配,与该案件相关的代码就会被执行。利用休息时间,避免因进入下一个代码自动执行。默认语句用于如果没有找到匹配。

例如




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

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