if / switch - “if $ var is'a'或'b'或'c'”等

时间:2010-10-19 09:05:12

标签: php if-statement

  

可能重复:
  PHP make if shorter

我有一个if语句,如下所示:

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

问题在于它变得非常沉重......它将成为大约20或30种不同的选择。

无论如何我能用更少的代码做到这一点吗? EG:

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

4 个答案:

答案 0 :(得分:5)

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  
}  

答案 1 :(得分:4)

最简单的想法是你创建一个这样的数组:

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

}else{

}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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