PHP – if…else…elseif


In this tutorial, you will learn about PHP if else statements and how they are used in the program. You’ll learn how to write decision-making code using if else if statements in PHP.

php if else statements

What is a control structure?
PHP If…else Statements

What is a control structure?

A control structure is a block of code that decides the execution path of a program depending on the value of the set condition., Code execution can be grouped into categories as shown below

Sequential – this one involves executing all the codes in the order in which they have been written.

Decision – this one involves making a choice given a number of options. The code executed depends on the value of the condition. This is where conditional statements like PHP if else are used.

PHP If Statements

PHP if statement, as the name suggests, is used to make a decision and execute a block of code if only the condition checked is matched.

It’s a one-way branching in which the statements will only execute if the given expression is true.

PHP If statement flowchart

php if statement flowchart
PHP if statement syntax

if (condition){
  //code to be executed 
}

PHP if statement example

<?php
$x = 10;
if ($x < 20){
  echo "Condition matched"; 
}
?>

Here the program will output “Condition matched”, since the condition checked by if statement is true.

PHP If else Statement

PHP if else statements are used when you want to execute some code if a condition is true and another code if a condition is false.

PHP if else syntax

if(condition){
   code to be executed if condition is true;
}else{
   code to be executed if condition is false;
}

PHP if else example

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

Output:

Have a good day!

PHP if..elseif..else statement

PHP if..elseif..else statement is used when you want to execute different code checking different conditions/

PHP if..elseif..else syntax

if(condition){
   code to be executed if condition is true;
}elseif(condition){
   code to be executed if condition is true;
}else{
   code to be executed if condition is false;
}

 

PHP if..elseif..else example

<?php

$d = date("D");

if ($d == "Fri"){
  echo "Have a nice weekend!";
}elseif ($d == "Sun"){
  echo "Have a nice Sunday!";
}else{
  echo "Have a nice day!";
}
?>

This example will output :

“Have a nice weekend!” if the current day is Friday

“Have a nice Sunday!” if the current day is Sunday.

Otherwise, it will output “Have a nice day!”