When is it best to use a switch statement in PHP?
In what circumstances should I be using a swit开发者_开发问答ch statement rather than if statements in PHP?
Never.
- You will forget the break statement at the end of a case, which can lead to undesired results.
- You can only evaluate one condition, an else-if is more versatile.
- It is ugly.
That said, sometimes you specifically need the fall-through functionality, or you return from the function in every case statement so that you can not forget the break. Maybe that warrants an exception.
You should be using a switch
statement when you have a sequence of if
s just testing one variable for different values. The switch statement is really just used to make your code look cleaner and be more clear, so if you feel like it does that, use it - your gut is probably right.
Switch should be used when you have a series of related conditionals that can be isolated logically or if you have a series of conditions that have to be executed based on the state or result of a singular variable or expression.
Contrary to other answers, the expression in the switch does not need to be isolated to a single variable (though it's simpler, easier to read, and generally a good idea), but the case statements need to generate individual results from the evaluated expression(s).
A good rule of thumb is to use switches when you have an easy to ready expression that will generate multiple results that you must then execute logic based upon. If your expressions are unrelated, result in boolean conditions only, or become complex/related (like if a then b, if c then b, if d then a sometimes b), then stick with ifs.
You use a switch when a certain variable could be one of many different "cases" In an IF statement, you could substitute this method with multiple ELSE IFs and very long conditionals if you needed.
There really isn't an easy way to answer this as there isn't a best time to use a switch. It is only when you show code that someone can say "That would work better with a switch." Still, in the end, you may only save a few milliseconds.
精彩评论