Conditional statements are used to perform different actions based on different conditions.
When you write code, you often need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In PHP, the following conditional statements are provided:
if statement - executes code when a condition is true
if...else statement - executes a block of code when a condition is true and another block of code when the condition is not true
if...elseif....else statement - executes a block of code when one of several conditions is true
switch statement - executes a block of code when one of several conditions is true
The if statement is used to execute code only when a specified condition is true .
if (condition){ code to be executed when the condition is true;}
If the current time is less than 20, the following example will output "Have a good day!":
<?php $t = date ( " H " ) ; if ( $t < " 20 " ) { echo " Have a good day! " ; } ?>
To execute a block of code when a condition is true and another block of code when the condition is not true , use the if....else statement.
if ( condition ) { code to be executed when the condition is true; }else { code to be executed when the condition is not true; }
The following example will output "Have a good day!" if the current time is less than 20, otherwise it will output "Have a good night!":
<?php $t = date ( " H " ) ; if ( $t < " 20 " ) { echo " Have a good day! " ; } else { echo " Have a good night! " ; } ?>
To execute a block of code when one of several conditions is true , use the if....elseif...else statement. .
if (condition){ code to be executed when the condition is true;}elseif (condition){ elseif code to be executed when the condition is true;}else{ code to be executed when the condition is not true;}
If the current time is less than 10, the following example will output "Have a good morning!", if the current time is not less than 10 and less than 20, it will output "Have a good day!", otherwise it will output "Have a good night!":
<?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! " ; } ?>
The switch statement will be explained in the next chapter.