PHP If Else語句
PHP if else語句用于測試條件。愛掏網(wǎng) - it200.com在PHP中,有多種方法可以使用if語句。愛掏網(wǎng) - it200.com
- if
- if-else
- if-else-if
- 嵌套if
PHP if語句允許根據(jù)條件執(zhí)行代碼。愛掏網(wǎng) - it200.com只有當(dāng)條件為真時才會執(zhí)行。愛掏網(wǎng) - it200.com
如果條件為真,則if語句中存在的代碼塊會被執(zhí)行。愛掏網(wǎng) - it200.com
語法
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語句
PHP if-else語句在條件為真或假時執(zhí)行。愛掏網(wǎng) - it200.com
if-else語句與if語句稍有不同。愛掏網(wǎng) - it200.com如果指定的條件為 true ,它將執(zhí)行一塊代碼;如果條件為 false ,則執(zhí)行另一塊代碼。愛掏網(wǎng) - it200.com
語法
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 語句
PHP的if-else-if是一種特殊的語句,用于組合多個if…else語句。愛掏網(wǎng) - it200.com因此,我們可以使用該語句來檢查多個條件。愛掏網(wǎng) - it200.com
語法
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語句
嵌套if語句是指if語句包含在另一個if語句中。愛掏網(wǎng) - it200.com內(nèi)部的if語句只在外部if語句的指定條件為 true 時執(zhí)行。愛掏網(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 開關(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
聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進行處理。