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

PHP if statement allows conditional execution of code. It is executed if the condition is true. The if statement is used to execute a block of code, present inside the if statement, if the specified condition is true.

#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

You can speed up the decision making process by providing an alternative option by adding an else statement to the if statement. The if...else statement allows you to execute a block of code if the specified condition evaluates to true and another block of code evaluates to false. It can be written as:

#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

When we want to execute different code for different conditions, and we have more than 2 possible conditions, we use if...elseif...else pair.

#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!".