user3092995
user3092995

Reputation: 43

PHP elseif statements; separate elseif, or compressed into one?

I'm basically wondering if there's a difference between enumerating all the possible conditions via separate elseif statements or combining them into one (apart from readability, that is).

Example 1:

if($x == 0)
{
    (condition A)
}
elseif($x == 1)
{
    (condition A)
}
elseif($x == 2)
{
    (condition A)
}
else
{
    (condition B)
}

Example 2:

if($x == 0 || $x == 1 || $x == 2)
{
    (condition A)
}
else
{
    (condition B)
}

Obviously example 2 is more readable, but is it also faster (or otherwise preferred)?

Upvotes: 0

Views: 65

Answers (3)

Nicholas Summers
Nicholas Summers

Reputation: 4756

You could also do:

if ($x <= 2) {
    // Condition A
} else {
    // Condition B
}

But to answer your question:

Of the 2 statements, theoretically the second would be faster but only because PHP would be parsing 1 statement recursively rather than 3 separate statements. However, the difference is so minuscule that you probably won't be able to accurately measure it. Which means they may as well be identical. My answer above this text would be faster than either of the supplied example because there is only 1 comparison (not 3). But again, the difference is small enough that it may as well be the same.

Upvotes: 2

mpen
mpen

Reputation: 283103

No, they're functionally equivalent.

Upvotes: 0

wavemode
wavemode

Reputation: 2116

The cleanest option I've seen for your code is the following:

switch($x) {
    case 0:
    case 1:
    case 2:
        (condition A)
        break;
    default:
        (condition B)
        break;
}

Upvotes: 2

Related Questions