if-elseif-else statement – this statement is used when we want to execute a code if one of multiple condition is true.
if-elseif-else statement syntax:
<?php
if (condition)
{
// if this condition is true then code to be executed
}
else if (condition)
{
// if this condition is true then code to be executed
}
else if (Condition)
{
// if this condition is true then code to be executed
}
else
{
// all conditions are false then this code to be executed
}?>
Example of if-elseif-else condition
In below example we calculate the grade for student, each student has only one grade from various grades like “first class”, “second class”, “pass class” etc.
Here we have various condition but output must be single so we need to use if-elseif-else condition for this php example.
<?php
$maths=60;
$biology=65;
$physics=73;$result = ($maths + $biology + $physics)/3;
if($result <35)
{
echo “Fail”;
}
else if($result>=35 && $result<=50)
{
echo “Pass class”;
}
else if($result>50 && $result<=60)
{
echo “Second class”;
}
else if($result>60 && $result<=70)
{
echo “First class”;
}
else //or else if($result>70)
{
echo “Distinction class”;
}
?>
The output is:
First class
In above php example the $result value is 66, the fourth condition is true and out put is “First class”.
Nice post that is really helpful thanks