We help IT Professionals succeed at work.

If Else IF an Else difference and whats the use of ElseIF

udara22
udara22 used Ask the Experts™
on
Hi, Can someone please tell me the difference between the 2 Scenarios below.

Scenario 1

if($number == '1')
elseif($number == '2')
elseif($number == '3')
else()

Scenario 2

if($number == '1')
if($number == '2')
if($number == '3')
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Engineer
Top Expert 2011
Commented:
In scenario 1 the elseif statements are only executed and condition tested if the IF Statement before it is false similarly the elseif lines are then only executed and condition tested if the elseif statement before it are false. The else statement will only be executed if all of the If and elseif conditions are false.

In scenario 2 each If statement will be executed and the condition tested.

So elseif provides a way of testing a further condition if the previous if or elseif condition returns false.
Commented:
In Scenario 1, at most ONE of the (do this) will be executed, namely the first one with a true IF condition.


In Scenario 2, each (do this) with a true condition would be executed.   All of them could be executed, if all of the IF conditions happened to be true.

Commented:
Hmmm, well, you changed the question slightly.

In the new version, where your IF conditions are testing the same variable for a specific number, all the IF conditions are mutually exclusive, so in this exact case, both scenarios are identical.

Author

Commented:
Ok. Thanks guys. This is all I need.