Conditional statements are used to perform different actions based on different conditions.
PHP conditional statements
When you write code, you often need to perform different actions for different judgments. You can use conditional statements in your code to accomplish this task.
In PHP, the following conditional statements are available:
- If statement -executes code when conditions are true
- If...else Statement -Executes a piece of code when the condition is set, and executes another piece of code when the condition is not true
- if...else If....else Statement -executes a block of code when one of several conditions is established
- switch Statement -executes a block of code when one of several conditions is established
Php-if statements
The IF statement is used to execute code only when the specified condition is true .
Grammar
1 if (condition) 2 {3 code to be executed when the condition is established; 4
If the current time is less than 20, the following instance will output "a good day!" :
1 <? PHP 2 $t=date("H"); 3 if ($t< ") 4 {5 Echo "A good day!" ; 6 }7 ?>
Php-if...else statements
Execute a piece of code when the condition is established, and execute another piece of code when the condition is not established , using the If....else statement.
Grammar
1 if (condition) 2 {3 code executed when the condition is established; 4 }5Else6 {7 The code executed when the condition is not established; 8
If the current time is less than 20, the following instance outputs "a good day!", otherwise the output "has a good night!" :
1<?PHP2 $t=Date("H");3 if($t< "20")4 {5 Echo"A good day!";6 }7 Else8 {9 Echo"A good night!";Ten}Php-if...else if....else Statements
To execute a block of code when one of several conditions is established , use the If....else if...else statement:
Grammar
1 if(condition)2 {3 ifcode executed when the condition is established;4 }5 Else if(condition)6 {7 ElseIfcode executed when the condition is established;8 }9 ElseTen { One code executed when the condition is not established; A}
If the current time is less than 10, the following instance outputs "a good morning!", and if the current time is not less than 10 and less than 20, the output "has a good
day! ", otherwise output" has a good night! " :
1<?PHP2 $t=Date("H");3 if($t< "10")4 {5 Echo"A good morning!";6 }7 Else if($t< "20")8 {9 Echo"A good day!";Ten } One Else A { - Echo"A good night!"; - } the?>
10. PHP Tutorial _php If ... Else statement