PHP Article

Conditional Statements

In this article we will discuss the 4 conditional statements used in PHP:
if, if...else, if...elseif...else, and the switch staterment.

This article assumes you have basic knowledge of HTML and PHP

if statement

The if statement executes some code if one condition is true

                    
                        
<?php
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
}
?>

OUTPUT:
Have a good day!
                                      
                

In the example above if the present hour is less then 20 Hours (10:00 PM) it will display the text.

if...else statement

The if...else statement executes some code if a condition is true and another code if that condition is false.

                    
                        
<?php
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>

OUTPUT if true:
Have a nice day!

OUTPUT if false:
Have a good night!
                                     
                

Here the answer is "Have a good night!" if it is 20 hours (10:00 PM) or later.

if...elseif...else statement

The if...elseif...else statement executes different codes for more than two conditions.

                    
                        
<?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 if first condition is true:
Have a good morning!

OUTPUT if second is true:
Have a good day!

OUTPUT if third is true:
Have a good night!
                                  
                

The example above evaluates three conditions and outputs the appropriate response depending on the time of day.

switch statement

Use the switch statement to select one of many blocks of code to be executed.

                    
                        
<?php
$favcolor = "Chevy";

switch ($favcolor) {
  case "Ford":
    echo "Your favorite car is a Ford!";
    break;
  case "Chevy":
    echo "Your favorite car is a Chevy!";
    break;
  case "":
    echo "Your favorite car is a Buick!";
    break;
  default:
    echo "Your favorite car is neither Ford, Chevy, nor Buick!";
}
?>

OUTPUT:
Your favorite car is a Chevy!
                                  
                

Here the switch statement selects the case indicated by the input (Chevy) Prints the text and breaks out of the statement using break statement we discuss in a different tutorial.

That's all there is to it! Happy Coding!