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

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 If...Else


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

The if, elseif and else statements in PHP are used to perform different actions based on different conditions.
PHP中的“if、elseif和else”的语句(即:条件语句),它是作用是根据不同的条件,执行不同的语句。


Conditional Statements
条件语句

Very often when you write code, you want to perform different actions for different decisions.
你在书写代码是经常会使用条件语句:

You can use conditional statements in your code to do this.
你可以在代码中可以使用的条件语句及功能如下:

  • if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
    if...else 语句:如果你希望在条件为真(true)或为假(false)时执行某段代码,你可以使用这个语句;
  • elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true
    elseif statement:这个语句是和if...else语句一起使用的。如果需要假设的条件不止一个时,可以使用这个语句;

The If...Else Statement
If...Else语句

If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.
如果你希望在条件为真(true)或为假(false)时执行某段代码,你可以使用if....else语句;

Syntax
语法

if (条件)
当条件为真代码就会执行;
else

当条件为假这段代码就会执行;

Example
案例

The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
如果今天是星期五,下面这个例子将输出“Have a nice weekend!”;否则,它将输出“Have a nice day!”:

<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>

If more than one line should be executed if a condition is true/false, the lines should be enclosed within curly braces:
在某一个条件(条件为真true/假false)的情况下,如果不止一条代码需要被执行,那么可以用大括号“{}”把它包含在内:

<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>


The ElseIf Statement
ElseIf语句

If you want to execute some code if one of several conditions are true use the elseif statement
如果需要假设的条件不止一个时,可以使用elseif语句。

Syntax
语法

if (条件1)
满足条件1时就执行这段代码;
elseif (条件2)

满足条件2时就执行这段代码;
else
两个条件都不满足的就执行这段代码;

Example
案例

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
如果今天是“星期五”,下面的例子将输出“Have a nice weekend!”;如果今天是“星期日”,下面的例子将输出“Have a nice Sunday!”;如果是其它情况则输出“Have a nice day!”:

<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>

评论 (0) All

登陆 | 还没注册?