开发者

if/switch - "if $var is 'a' or is 'b' or is 'c'" etc [duplicate]

This question already has answers here: Closed 12 years ago.

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开发者_JAVA技巧" || "three" || "four" || "five"))..


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  
}  


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{

}


switch ($i) {
case "one":
case "two":
case "three":
.
.
.
//Code here
break;
}


if (preg_match('/^(one|two|three|four|five)$/', $var)) {
    // Do stuff
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜