When is the best time to use a switch statement in PHP?
A switch should be used when you have a set of related conventions that can be isolated logically, or when you have a set of conditions that must be met based on the state or result of a singular variable or expression.
Unlike other answers, an expression in a commutator does not have to be isolated from a single variable (although it is simpler, easier to read, and generally a good idea), but case statements should generate separate results from the evaluated expression (s).
A good rule of thumb is to use radio buttons when you have an easy-to-read expression that will generate multiple results that must then be executed based on logic. If your expressions are not related to each other, they only lead to boolean conditions, or become complex / chained (e.g. if a then b, if c then b, if d then sometimes b) then stick with ifs.
source to share
You are using a switch when a certain variable can be one of many "cases". In an IF statement, you can replace this method with multiple ELSE IFs and very long conditional statements if you need to.
There is really no easy way to answer this because there is no better time to use the switch. It's only when you show the code that someone can say "This will work better with the switch." However, in the end, you can only save a few milliseconds.
source to share
Never.
- You will forget the break statement at the end of the case, which can lead to unwanted results.
- You can only evaluate one condition, another if it is more universal.
- It's not beautiful.
However, you sometimes need the fail function, or you return from the function on every occasion so you can't forget the break. Perhaps this guarantees an exception.
source to share