PHP if...else...elseif Statements
When writing a program/script, there will be scenarios where you would like to execute a particular statement only if some condition is met. In such situations we use conditional statements.
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
In PHP we have the following conditional statements:
1. if statement - executes some code if one condition is true
2. if...else statement - executes some code if a condition is true and another code if that condition is false
3. if...elseif...else statement - executes different codes for more than two conditions
PHP If statement
#Syntax if(condition){ //code to be executed } #Example <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?> #Output Output "Have a good day!" if the current time (HOUR) is less than 20.
PHP If-else Statement
#Syntax if(condition){ // Code to be executed if condition is true } else{ // Code to be executed if condition is false } #Example <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> #Output Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise.
PHP if...elseif...else Statement
#Syntax if (condition) { code to be executed if this condition is true; } elseif (condition) { code to be executed if first condition is false and this condition is true; } else { code to be executed if all conditions are false; } #Example <?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!"; } ?> #Output Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!".