PHP If else

In this lesson, you will learn about the condition statement if..else in PHP, its usage, along with examples to better understand the topic.


if…else in PHP

If…else is a vital control statement that every developer should know. If you have a code block that should only be executed if a specific circumstance is true, or execute the else part of the code if the condition is false.

Basic Syntax of if..else

<?php
if (condition is true) {
    //block one will be executed if condition is true
}else{
    //block two will be executed if condition is false
}
?>

If the condition is true, the "block one" will be executed. Else, block two will be executed.

Flowchart of if..else

 

Example

<?php
echo "PHP *** If else Statement*** ";
echo "<br>";
echo "****** Example (1)******* ";
echo "<br>";
$var = 13;
echo " Number = ", $var;
echo "<br>";
if ($var % 2 == 0) {
    echo "Divisble by 2. Its Even number <br />";
} else {
    echo "Not Divisble by 2 . Its an odd number<br />";
}
echo "<br>";
echo "****** Example (2)******* ";
echo "<br>";
$istnumber = 107;
$secnumber = 201;
echo " ist Number = ", $istnumber, "</br>", " 2nd Number = ", $secnumber;
echo "<br>";
if ($istnumber > $secnumber) {
    echo "ist Number $istnumber is greater than 2nd Number $secnumber";
} else {
    echo "2nd Number $secnumber is greater than ist Number $istnumber";
}
?>

Output

PHP *** If else Statement***
****** Example (1)*******
Number = 13
Not Divisble by 2 . Its an odd number

****** Example (2)*******
ist Number = 107
2nd Number = 201
2nd Number 201 is greater than ist Number 107

This concludes the PHP if…else lesson. In the next lesson, we will explain another control statement in PHP, which is the if…else…if else.