Conditional statements based on different conditions to perform different actions
PHP conditional statements
When you write code, often you want to perform different actions for different decisions. You can do this using conditional statements in the code.
In PHP, we can use the following conditional statement:
- if statement - if the specified condition is true, execute the code
- if ... else statement - if the condition is true, the code is executed; if the condition is false, the code is executed and the other end
- if ... elseif .... else statement - execute different code blocks according to the above two conditions
- switch statement - selecting one of the plurality of code blocks is performed
PHP - if statement
if statement is true specified condition code execution.
grammar
if (condition) { code is executed when the condition is true; }
The following example will output "Have a good day!", If the current time (HOUR) is less than 20:
Examples
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?>
PHP - if ... else statement
Please use the if .... else statement to execute code when conditions are to true , perform another piece of code is false condition .
grammar
if (condition) { Code execution condition is true; } the else { code is executed when the condition is false; }
If the current time (HOUR) is less than 20, the example will output "Have a good day!", And otherwise outputs "Have a good night!":
Examples
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - if ... elseif .... else Statement
Please use the if .... elseif ... else statement to execute different code based on the above two conditions .
grammar
if (condition) { Code execution condition is true; } ELSEIF (for condition Condition) { Code execution condition is true; } the else { code is executed when the condition is false; }
If the current time (HOUR) is less than 10, the example will output "Have a good morning!", If the current time is less than 20, then the output "Have a good day!". Otherwise it will output "Have a good night!":
Examples
<?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } elseif ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - switch statement
We learn a switch statement in the next section.