PHP If Else Statement

In this tutorial, you will learn how to use the If Else statement for decision-making in PHP.


If Else Statement controls the execution of the program based on the evaluation of the conditional statement. PHP if else statement works similar to most of the programing language. This means you can create a conditional statement in your program and based on the result of the statement which is either true or false, you can perform certain actions.

There are few variations of the If Else Statement in PHP by which you can write conditional statements in PHP.

  • The if statement
  • The if…else statement
  • The if…elseif….else statement
  • The nested if statement

PHP If statement

This is the simplest PHP conditional statement. PHP If condition will execute the codes inside the block only if the If condition evaluates true.

Syntax

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

Example

<?php
$num1=10;
$num2=20;
if($num1<$num2){
echo "$num1 is smaller than $num2";
}
?>

Output

10 is smaller than 20

PHP If Else Statement

If you proceed one step ahead of PHP If statement, it is PHP If Else statement. Unlike PHP If where the certain block will be executed only if the condition is true, PHP If else statement allows you to execute one block of code if the condition is true and another block of code if the condition is false.

Syntax

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

Example

<?php
$num=15;
if($num<10){
echo "$num is smaller than 10";
}
else {
echo "$num is greater than 10";
}
?>

Output

15 is greater than 10

PHP If Elseif Else Statement

PHP If Elseif Else is a special statement that provides us the facility to check multiple if-else conditions in condition.

Syntax

if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}

Example

<?php
$marks=88;
if($marks>90){
print("Grade: A+");
}
else if($marks>75){
print("Grade: A");
}
else if($marks>60){
print("Grade: B");
}
else{
print("Grade: C");
}
?>

Output

Grade: A

PHP Nested If Statement

PHP Nested If contains another If statement inside the regular If statement. The inner If statement will only execute if the outer If statement becomes true.

Syntax

if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if both if conditions are true
}
}

Example

<?php 
$age = 28; 
$nationality = "Indian"; 
//applying conditions on nationality and age 
if ($nationality == "Indian") 
{ 
if ($age <= 30) { 
echo "You are Eligible to write the exam"; 
} 
else { 
echo "Not eligible to write the exam"; 
} 
} 
?>

Output

You are Eligible to write the exam

Please get connected & share!

Advertisement