views:

46

answers:

4

Possible Duplicate:
PHP make if shorter

I have an if statement that looks like this:

if($variable == "one" || $variable == "two" || $variable == "three" || $variable == "four"){
    // do something
}
else {
    // do something else
}

the problem is that its getting quite hefty.. its going to be about 20 or 30 different options.

Is there anyway I can do this in less code? EG:

if($variable == ("one" || "two" || "three" || "four" || "five"))..

+3  A: 

The simplest thing that comes to mind is is that you create an array like this:

$options = array("one" , "two" , "three" , "four" , "five");
if(in_array($variable , $options)){

}else{

}
Sabeen Malik
+4  A: 
switch ($variable) {
 case "one":
 case "two":
 case "three":
 case "four": 
    // do something 
    break; 
 default:
    // do something else 
} 

OR

$testSeries = array("one","two","three","four");
if (in_array($variable,$testSeries)) {
    // do something  
}  
else {  
    // do something else  
}  
Mark Baker
ah, does the first option work! :p didn't try that. I did think about using a switch statement but didn't wanna have to replicate the code for each `case`. :) Thank you.
Thomas Clayson
@Thomas: Mark's switch statement works because the `break` statements are omitted from all but the last case, so the code would go all the way down to the last case and execute its code too, until it finally encounters the `break` statement underneath that.
BoltClock
ah i see... that was brilliant :)
Thomas Clayson
A: 
switch ($i) {
case "one":
case "two":
case "three":
.
.
.
//Code here
break;
}
Tokk
A: 
if (preg_match('/^(one|two|three|four|five)$/', $var)) {
    // Do stuff
}
Petah