PHP教程
PHP Mysql
PHP面向对象
PHP常用

PHP 如果其他

PHP If Else

PHP if else 语句用于测试条件。 PHP 中有多种使用 if 语句的方法。
if if-else if-else-if 嵌套 if

PHP If 语句

PHP if 语句允许有条件地执行代码。如果条件为真则执行。
If 语句用于仅当指定的条件为真时才执行 if 语句中存在的代码块。
语法
if(condition){
//code to be executed
}
流程图
php if 语句流程图
示例
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
输出:
12 is less than 100

PHP If-else 语句

PHP if-else 语句无论条件为真还是假都执行。
If-else 语句与 if 语句略有不同。如果指定条件为真,则执行一个代码块,如果条件为假,则执行另一块代码。
语法
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
流程图
php if-else 语句流程图
示例
<?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 语句。因此,我们可以使用此语句检查多个条件。
语法
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 if-else 语句流程图
示例
<?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 块。内部 if 语句仅在外部 if 语句中指定的条件为 true 时才执行。
语法
if (condition) {  
//code to be executed if condition is true 
if (condition) {  
//code to be executed if condition is true  
}  
} 
流程图
php if-else 语句流程图
示例
<?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 开关示例
<?php
              $a = 34; $b = 56; $c = 45;
	if ($a < $b) {
		if ($a < $c) {
			echo "$a is smaller than $b and $c";
		}
	}
?>
输出:
34 is smaller than 56 and 45
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4