If、elseif 以及 else 語(yǔ)句用于執(zhí)行基于不同條件的不同動(dòng)作。
條件語(yǔ)句
當(dāng)您編寫代碼時(shí),您常常需要為不同的判斷執(zhí)行不同的動(dòng)作。您可以在代碼中使用條件語(yǔ)句來完成此任務(wù)。
if...else 語(yǔ)句
在條件成立時(shí)執(zhí)行一塊代碼,條件不成立時(shí)執(zhí)行另一塊代碼
elseif 語(yǔ)句
與 if...else 配合使用,在若干條件之一成立時(shí)執(zhí)行一個(gè)代碼塊
If...Else 語(yǔ)句
如果您希望在某個(gè)條件成立時(shí)執(zhí)行一些代碼,在條件不成立時(shí)執(zhí)行另一些代碼,請(qǐng)使用 if....else 語(yǔ)句。
語(yǔ)法
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
|
實(shí)例
如果當(dāng)前日期是周五,下面的代碼將輸出 "Have a nice weekend!",否則會(huì)輸出 "Have a nice day!":
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!
";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
|
ElseIf 語(yǔ)句
如果希望在多個(gè)條件之一成立時(shí)執(zhí)行代碼,請(qǐng)使用 elseif 語(yǔ)句:
語(yǔ)法
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
|
實(shí)例
如果當(dāng)前日期是周五,下面的例子會(huì)輸出 "Have a nice weekend!",如果是周日,則輸出 "Have a nice Sunday!",否則輸出 "Have a nice day!":
<?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!";
?>