当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > PHP Switch

PHP
PHP 介绍
PHP 安装
PHP 语法
PHP 变量
PHP操作符
PHP If...Else
PHP Switch
PHP 数组
PHP 循环
PHP 函数
PHP 表单
PHP $_GET
PHP $_POST
PHP Date
PHP Include
PHP 文件处理
PHP 文件上传
PHP Cookies
PHP Sessions
PHP 发送邮件

PHP Switch


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-01   浏览: 1551 ::
收藏到网摘: n/a

The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions.
PHP Switch语句的作用是:根据不同的条件,执行不同的语句。


The Switch Statement
Switch语句

If you want to select one of many blocks of code to be executed, use the Switch statement.
如果你想同时判断多种条件,并执行其中一种符合条件的代码,那么可以使用“switch”语句。

The switch statement is used to avoid long blocks of if..elseif..else code.
使用switch语句可以避免同时使用多个“if...elseif...else”代码,现在较为简便。

Syntax
语法

switch (表达式)
{
case label1:
当 表达式 = label1 时就执行这段代码;
break;
case label2:

当 表达式 = label2 时就执行这段代码;
break;
default:
当表达式为其它情况的时候就执行这段代码;
}

Example
案例

This is how it works:
下面介绍它的工作原理:

  • A single expression (most often a variable) is evaluated once
    逐个地执行条件中预先设定的表达式或计算变量;
  • The value of the expression is compared with the values for each case in the structure
    将条件中预先设定的表达式或变量的值与代码中设定的条件相比较;
  • If there is a match, the code associated with that case is executed
    如果上述二者匹配,那么与这个条件相关的代码将被执行;
  • After a code is executed, break is used to stop the code from running into the next case
    在一段符合条件的代码被执行以后,可以使用“break”跳出Switch语句;
  • The default statement is used if none of the cases are true
    当所有的条件都是假[false]时,则执行default语句;
<html>
<body>
<?php
switch ($x)
{
case 1:
echo "数字 1";
break;
case 2:
echo "数字 2";
break;
case 3:
echo "数字 3";
break;
default:
echo "这个数不等于1、2和3";
}
?>
</body>
</html>

评论 (0) All

登陆 | 还没注册?