在PHP中,有一种简短的方法可以将变量与多个值进行比较吗?

时间:2013-05-02 19:05:13

标签: php variables comparison shorthand

基本上我想知道是否有办法缩短这样的东西:

if ($variable == "one" || $variable == "two" || $variable == "three")

以这种方式可以对变量进行测试或与多个值进行比较,而不必每次都重复变量和运算符。

例如,某些内容可能会有所帮助:

if ($variable == "one" or "two" or "three")

或任何导致输入较少的内容。

5 个答案:

答案 0 :(得分:34)

我正在使用

in_array()

if (in_array($variable, array('one','two','three'))) {

答案 1 :(得分:4)

无需构建数组:

if (strstr('onetwothree', $variable))
//or case-insensitive => stristr

当然,从技术上讲,如果变量为twothr,则返回true,因此添加“分隔符”可能很方便:

if (stristr('one/two/three', $variable))//or comma's or somehting else

答案 2 :(得分:0)

$variable = 'one';
// ofc you could put the whole list in the in_array() 
$list = ['one','two','three'];
if(in_array($variable,$list)){      
    echo "yep";     
} else {   
    echo "nope";        
}

答案 3 :(得分:0)

带开关盒

switch($variable){
 case 'one': case 'two': case 'three':
   //do something amazing here
 break;
 default:
   //throw new Exception("You are not worth it");
 break;
}

答案 4 :(得分:0)

使用preg_grep可能比使用in_array更短,更灵活:

if (preg_grep("/(one|two|three)/i", array($variable))) {
  // ...
}

因为可选的i pattern modifier i nsensitive)可以匹配大写和小写字母。