Under what conditions should I use an if-else-if ladder instead of a switch when coding a multipath branch?
Answer:
In general, use an if-else-if ladder when the conditions controlling the selection process do not depend on a single value.
Example:
if(x < 10) // ...
else if(y != 0) // ...
else if(!done) // ...
This sequence cannot be recoded with a switch because all three conditions involve different variables – and different types. What variable would control the switch?
You will also have to use an if-else-if ladder when testing floating point values or other objects that are not valid types in a switch expression.
The above is the detailed content of Ask the Expert - If/else or switch. For more information, please follow other related articles on the PHP Chinese website!