Forum Moderators: coopster
Conclusion: switch ;)
As far as readability, if/elseif/else is plenty readable and takes less lines of code. The reason being, to stop the switch() from evaluating every case(even after a match) you need a break line in each one. if(), however, will stop automatically after a match
if ($a == $b) {
echo 'a = b';
} elseif ($a == $c) {
echo 'a = c';
} elseif ($a == $d) {
echo 'a = d';
} else {
echo 'a = a';
}
switch($a) {
case $b:
echo 'a = b';
break;
case $c:
echo 'a = c';
break;
case $d:
echo 'a = d';
break;
default:
echo 'a = a';
}
often switch can't be adopted if there are multiple else statements on those ifs
I think I understand what you are getting at but there actually is a trick to that. You can reverse the expression/value (they are both acceptable in either place, the switch expression/value or the case expression/value, as long as the case evaluates to a simple type -- and this case you would use a boolean value in the switch expression when you know that the case statements are structured to return a true/false boolean simple type). Some examples ...
[webmasterworld.com...]
[webmasterworld.com...]
If I'm off-base, forgive me, but at least here are some examples for those that have never considered this possibility.
I was just thinking structure wise based on this statement
>> Assuming an environment that calls for many "if"
if you have
if
if
if
probably could be a switch if there is corelation between conditions
if you have
if
else if
else if
else
this is exactly what a switch is and, in my mind, these should always be made into switches
if you have
if else
if else
if else
even with conditional corelation these are tricky, your method is one way but sometimes they are just better as is
I just didn't want people to think
multiple ifs == switch
it doesn't work quite that simply