Both are efficient and both have their own different use.
Using If else if
. For example if the requirement or problem is finding if a number is odd or even:
$num = 0
if($num == 0)
// print 'neutral'
else if($num % 2 == 0)
// print even
else
// print odd
output:
neutral
As you can see in the above example, If one condition satisfy, we do not need to compare it to other condition for we already have the answer, its waste of resources and will yield incorrect result if we do:
$num = 0
if($num == 0)
// print neutral
if($num % 2 == 0)
// print even
if($num % 2 != 0)
// print odd
output :
neutral
even
Using Ifs
. Another real life example might be if you are comparing 3 numbers and checking which one is largest:
$num1 = 2
$num2 = 30
$num3 = 31
$large = $num1
if($num2 > $large)
$large = $num2
if($num3 > $large)
$large = $num3
output:
largest is $num3 or 31
as you can see in the above example, we need to compare all of the numbers to get the largest. If we do this we will yield incorrect result:
$num1 = 2
$num2 = 30
$num3 = 31
$large = $num1
if($num2 > $large)
$large = $num2
else if($num3 > $large)
$large = $num3
output:
largest is $num2 or 30
else if
should be definitely better as once the condition is true, rest of the evaluations will be skipped.x=1
, do you?else if
.