PHP Condition Statement: IF Else And Switch Case

Objective

What is Conditional Statement in PHP?
How many types of conditional statements are there in PHP?
Programming Example of Conditional Statement.

WHAT IS CONDITIONAL STATEMENT IN PHP?

Conditional Statements are used when you need to make decision pragmatically. If Else and Switch Case are the main Conditional Statement in PHP that executes certain block of codes based on matched condition. For Example,

You have a list of Items for Male and Female and you want to show the only item based on gender.

HOW MANY TYPES OF CONDITIONAL STATEMENTS ARE THERE IN PHP?

You can use following decision-making keyword in PHP.
  1. if Statement
  2. if else Statement
  3. if elseif else Statement
  4. switch case statement

IF STATEMENT

It executes a block of codes if condition matched.

Example
<?php
  $x=5;
  $y=10;
  
  if($x!=$y)
  {
   echo $x." is not equal to ".$y;
  }
?>
Output
5 is not equal to 10

IF ELSE STATEMENT

There is two blocks of codes in IF Else statement. If condition matches then IF block gets executed otherwise Else block gets executed.

Example
<?php
  $x=5;
  $y=10;
  
  if($x==$y)
  {
   echo $x." is equal to ".$y;
  }
  else 
  {
   echo $x." is not equal to ".$y;
  }
?>
Output
5 is not equal to 10

IF ELSEIF ELSE STATEMENT

If there are multiple conditions to be tested then If ElseIF Else statement is used.

Example
<?php
  $x=5;
  $y=10;
  
  if($x == $y)
  {
   echo $x." is equal to ".$y;
  }
  elseif($x > $y)
  {
   echo $x." is greater than ".$y;
  }
  elseif($y % 2 == 0)
  {
   echo $y." is an even number";
  }
  else 
  {
   echo $x." is not equal to ".$y;
  }
   
?>
Output
10 is an even number

SWITCH CASE STATEMENTS

If there are multiple conditions then Switch Case is the best way to test them.

Example
<?php
  $day="Sunday";
  
  switch($day)
   {
   case "Monday":
   echo "This is Monday";
   break;
   
   case "Wednesday":
   echo "This is Wednesday";
   break;
   
   case "Friday":
   echo "This is Friday";
   break;
   
   case "Sunday":
   echo "This is Sunday";
   break;
   
   default:
   echo "Days not found";
   }
?>
Output
This is Sunday

SUMMARY

In this chapter, you learned PHP Condition Statement like If Else and Switch Case with programming example. The examples are very basic and our motive is to teach you conditional statement with easy programming example. In the next chapter, you will learn Loops in PHP.