What is the best alternative of using several (23 in my case) if-elseif
nested loops in PHP?
The switch statement will do it. http://php.net/manual/en/control-structures.switch.php
If performance is your concern, if
statements use check followed by a jump to the next clause where as in a switch
the value is loaded first, compared and iterated through the value table to find a match, which is faster in most cases.
For readability I think switch
is better when you have more than two conditions.
But primarily everything depends on the usage circumstance.
If you are in doubt of which to choose:
Choose switches
when you have an easy to read 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. (As said here)