In this lesson, you will learn about the if…elseif…else control statement in PHP, and its usage, along with examples to better understand the topic.
You can use the if…elseif…else statement if you have more than two conditions to validate.
if(condition1){ // Block of Code will be processed if condition1 is true } elseif(condition2){ // Block of Code will be processed if the condition1 is false and condition2 is true } else{ // Block of Code will processed if both condition1 and condition2 are false }
Example
<?php echo "PHP *** If else if else Statement*** "; echo "<br>"; echo "****** Example (1)******* "; echo "<br>"; $var = 155; echo " Number = ", $var; echo "<br>"; if (($var % 2) == 0) { echo 'Divisble by 2. Its Even number <br />'; } else if (($var % 2) != 0) { echo 'Not Divisble by 2 . Its an odd number<br />'; } else { echo 'Null is passed<br />'; } echo "<br>"; echo "****** Example (2)******* "; echo "<br>"; $istnumber = 200; $secnumber = 200; echo " ist Number = ", $istnumber, "</br>", " 2nd Number = ", $secnumber; echo "<br>"; if ($istnumber > $secnumber) { echo "ist Number $istnumber is greater than 2nd Number $secnumber"; } else if ($istnumber < $secnumber) { echo "2nd Number $secnumber is greater than ist Number $istnumber"; } else { echo "2nd Number $secnumber is equalto ist Number $istnumber"; } ?>
Output
PHP *** If else if else Statement*** ****** Example (1)******* Number = 155 Not Divisble by 2 . Its an odd number ****** Example (2)******* ist Number = 200 2nd Number = 200 2nd Number 200 is equalto ist Number 200
This concludes the PHP if…elseif…else lesson. In the next lesson, we will discuss the switch statement in the PHP.