Reputation: 637
I found this post: Switch case with three parameters? and I was considering using switch case passing multiple parameters like this:
switch (array($var1, $var2, $var3)) {
case array(true, false, false):
echo "hello";
break;
}
There seems to be some question as to whether this is the most efficient way of doing this. The mood seems to be that an if conditional is more appropriate. But, when I look at the conditional I'm writing, I'm not sure? For example this feels messy (note that I've removed about 6 other conditionals to keep from boring you):
if (
csz == "google" ||
csz == "bing" ||
csz == "yahoo" ||
csz == "dogpile" ||
csz == "millionshort" &&
cs == '' ) {
$("li.phone").replaceWith('<li class="phone">' + phoneNaturalSearch + '</li>');
}
else if (
csz == "facebook" &&
cs == '' ) {
$("li.phone").replaceWith('<li class="phone">' + phoneFacebook + '</li>');
}
else if (
csz == "google-plus" ||
csz == "plus" ) {
$("li.phone").replaceWith('<li class="phone">' + phoneGooglePlus + '</li>');
}
// Snipped out other conditionals
else {
$("li.phone").replaceWith('<li class="phone">' + phoneDefault + '</li>');
}
Would switch with multiple parameters be more efficient here, or would I experience a performance hit? I guess I should write the code and see if it's actually less messy, but I thought I'd bounce it off of the gurus first.
Upvotes: 0
Views: 1438
Reputation: 1492
Talking about neater solutions, another way of doing it is to keep them in a 2 dimensional array and retrieving the element index.
Check this out :
var csz= 'amazon';
var groups = [['google','yahoo','bing'],['facebook','orkut','hi5','zurker'],['amazon','bestbuy','sears']];
var groupIndex = getIndexOf(groups,csz);
if(groupIndex ==1){
//code here
alert("1");
}else if(groupIndex ==2){
//code here
alert("2");
}else if(groupIndex ==3){
//code here
alert("3");
}
function getIndexOf(myArray,element){
for(var i=0;i<groups.length;i++){
for(var j=0;j<groups[i].length;j++){
if(myArray[i][j]==element){
return i;
}
}
}
return -1;
}
Upvotes: 0
Reputation: 55750
I feel if you have these many conditions I prefer to use switch statements which makes your code cleaner and easier to understand.. You can omit the break's for the conditions that fall for this particular category...
var phoneType= '';
switch(csz){
case "google" :
case "bing" :
case "yahoo" :
case "dogpile" :
case "millionshort" :
if (cs==''){
phoneType = phoneNaturalSearch ;
break;
}
else {
goto case "facebook";
}
case "facebook" :
if (cs==''){
phoneType = phoneFacebook ;
break;
}
else {
goto case "google-plus";
}
case "google-plus" :
case "plus" :
phoneType = phoneGooglePlus ;
break;
default :
phoneType = phoneDefault ;
break;
}
$("li.phone").replaceWith('<li class="phone">' + phoneType + '</li>');
Upvotes: 5