if/switch - "if $var is 'a' or is 'b' or is 'c'" etc [duplicate]
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
}
精彩评论