...

View Full Version : elseif or switch/case ?



sitNsmile
04-01-2010, 12:06 AM
Okay, whats the difference of using either or? cons/pros ? I believe they almost can have the same idea, I'd rather use "switch/case" but wanted to see what everyone else thought about it


i'd prefer.


switch($order)
{
case 'ID':$gameOrder = $this->type0;break;
case 'DATE':$gameOrder = $this->type1;break;
case 'RANDOM':$gameOrder = $this->type2;break;
case 'RATING':$gameOrder = $this->type3;break;
case 'TOTALPOPULAR':$gameOrder = $this->type4;break;
case 'TODAYPOPULAR':$gameOrder = $this->type5;break;
}


or



if($type=='ID'){$type = $this->type0;}
elseif($type=='DATE'){$type = $this->type1;}
elseif($type=='RANDOM'){$type = $this->type2;}
elseif($type=='RATING'){$type = $this->type3;}
elseif($type=='TOTALPOPULAR'){$type = $this->type4;}
elseif($type=='TODAYPOPULAR'){$type = $this->type5;}
else{$type = $this->type1;
}

cfructose
04-01-2010, 12:35 AM
They're exact equivalents, but the switch-case structure is less verbose.

Personally, I use switches a lot. They just seem neater somehow, and certainly reduce the amount that needs to be typed. I also find them easier on the eye structurally.

Another benefit of the switch structure is the possibility of catching everything you don't explicitly cater for with a "default". This, of course, is no different from a final "else {}", but the word "default", again for aesthetic purposes, but also semantically, seems very appealing to me.

I've never done a benchtest for speed comparison, but I presume that if you're only checking a handful of things, the difference would be infinitesimal either way.

Len Whistler
04-01-2010, 02:37 AM
I don't see much - if any - advantage switch has over if, even with lots of options in the statement. One big disadvantage with switch is the limited math functions you can use.


switch(very little math functions)

if (lots of math functions)




-----------------

kbluhm
04-01-2010, 02:41 AM
I don't see any advantage switch has over if, even with lots of options in the statement. One big disadvantage with switch is the limited math functions you can use with it:


switch(very little math functions)

if (lots of math functions)

That is fairly simple:


switch ( TRUE )
{
case isset( $this ) && 1 == $this:
// execute this
break;
case isset( $that ) && 1 == $that:
// execute that
break;
default:
// execute default
}


switch() is also faster that if(), elseif(), else



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum