Home  >  Article  >  php教程  >  PHP中Switch语句的用法示例

PHP中Switch语句的用法示例

WBOY
WBOYOriginal
2016-06-06 19:56:071910browse

PHP 中的 Switch 语句用于执行基于多个不同条件的不同动作。 Switch 语句 如果您希望有选择地执行若干代码块之一,请使用 Switch 语句。 使用 Switch 语句可以避免冗长的 if..elseif..else 代码块。 语法 switch (expression) { case label1: code to be exe

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

PHP中Switch语句的用法示例

Statement:
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