0

I love getting myself into these ridiculous situations where I over-evaluate my coding practices, so here goes!

This question probably transcends PHP (as well as sanity). When evaluating a Boolean variable, which of these is best practice? (assume that there's too much //do stuff for a ternary)

if ($bool) {
    // do true stuff
} else {
    // do false stuff
}

or

switch ($bool) {
    case true:
        // do true stuff
        break;
    default:
        // do false stuff
        break;
}

I'm interested more in performance and/or idiosyncratic considerations than blanket statements like "If/Else looks better," "Always use Switch," or "Do what you feel is right."

That is, unless there really isn't a difference.

1
  • 5
    Why are people so anal about performance of these things? Commented Aug 27, 2010 at 15:47

2 Answers 2

10

Use the if-else version. It's very clear and easy to understand.

You shouldn't really use switch unless you have multiple (> 2) values to switch on. You gain nothing using switch in this case (other than making your code less comprehensible).

If there was any difference in performance, the if-else version would be faster, although if was there any difference it would really be negligible.

This would be a micro-optimization if anything. Don't do it. Before you introduce any "optimizations" to your code, profile it and identify your bottlenecks.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. For what it's worth I'm not profiling my code afterward and thinking "Man I wonder what would be faster." It was more of a "What should I tend to do when writing the conditional in the first place."
0

Just in case, you should also check that your variable is really a boolean (and not "", 0, or null which may also evaluate to false)

if($bool === false) {
 // false stuff
} else if($bool === true) {
 // true stuff
} else {
 /// WTF???
}

1 Comment

else { throw FileNotFoundException }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.