PHP If Else語(yǔ)句
PHP if else語(yǔ)句用于測(cè)試條件。愛(ài)掏網(wǎng) - it200.com在PHP中,有多種方法可以使用if語(yǔ)句。愛(ài)掏網(wǎng) - it200.com
- if
- if-else
- if-else-if
- 嵌套if
PHP if語(yǔ)句允許根據(jù)條件執(zhí)行代碼。愛(ài)掏網(wǎng) - it200.com只有當(dāng)條件為真時(shí)才會(huì)執(zhí)行。愛(ài)掏網(wǎng) - it200.com
如果條件為真,則if語(yǔ)句中存在的代碼塊會(huì)被執(zhí)行。愛(ài)掏網(wǎng) - it200.com
語(yǔ)法
if(condition){
//code to be executed
}
流程圖
示例
<?php
num=12;
if(num<100){
echo "$num is less than 100";
}
?>
輸出:
12 is less than 100
PHP If-else語(yǔ)句
PHP if-else語(yǔ)句在條件為真或假時(shí)執(zhí)行。愛(ài)掏網(wǎng) - it200.com
if-else語(yǔ)句與if語(yǔ)句稍有不同。愛(ài)掏網(wǎng) - it200.com如果指定的條件為 true ,它將執(zhí)行一塊代碼;如果條件為 false ,則執(zhí)行另一塊代碼。愛(ài)掏網(wǎng) - it200.com
語(yǔ)法
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
流程圖
示例
<?php
num=12;
if(num%2==0){
echo "num is even number";
}else{
echo "num is odd number";
}
?>
輸出:
12 is even number
PHP If-else-if 語(yǔ)句
PHP的if-else-if是一種特殊的語(yǔ)句,用于組合多個(gè)if…else語(yǔ)句。愛(ài)掏網(wǎng) - it200.com因此,我們可以使用該語(yǔ)句來(lái)檢查多個(gè)條件。愛(ài)掏網(wǎng) - it200.com
語(yǔ)法
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
流程圖
示例
<?php
marks=69; if (marks<33){
echo "fail";
}
else if (marks>=34 &&marks<50) {
echo "D grade";
}
else if (marks>=50 &&marks<65) {
echo "C grade";
}
else if (marks>=65 &&marks<80) {
echo "B grade";
}
else if (marks>=80 &&marks<90) {
echo "A grade";
}
else if (marks>=90 &&marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
輸出:
B Grade
PHP 嵌套if語(yǔ)句
嵌套if語(yǔ)句是指if語(yǔ)句包含在另一個(gè)if語(yǔ)句中。愛(ài)掏網(wǎng) - it200.com內(nèi)部的if語(yǔ)句只在外部if語(yǔ)句的指定條件為 true 時(shí)執(zhí)行。愛(ài)掏網(wǎng) - it200.com
句法
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
流程圖
示例
<?php
age = 23;nationality = "Indian";
//applying conditions on nationality and age
if (nationality == "Indian")
{
if (age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
輸出:
Eligible to give vote
PHP 開(kāi)關(guān)示例
<?php
a = 34;b = 56; c = 45;
if (a < b) {
if (a < c) {
echo "a is smaller than b andc";
}
}
?>
輸出:
34 is smaller than 56 and 45