php - Is switch always better than a lot of elseifs?

Solution:
Switch is really good in some situations but really bad for others. In your specific situation I would use if/elseif conditions.
I useswitch
when the condition is simple and the expression is simple. If the condition has more than one variable and the expression is longer than about three lines I wouldn't use a switch.
Here's a good example of a good switch:
switch ( $type ) {
case 'banana':
$valid = true;
$price = 1;
break;
case 'apple':
$valid = false;
$price = 2.52;
break;
}
Answer
Solution:
It's about readability and taste for the most part, quite honestly. I prefer elseif statements because it allows for more flexibility if conditions become more complex.
Answer
Solution:
To optimize your code, you want to put the most frequently usedif
statements at the top of the block ofelseif
statements. Otherwise, the only difference is in readability of your code, which is actually a great reason to useswitch
statments.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: unable to determine current zabbix database version: the table "dbversion" was not found.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.