在PHP中,是否有一种简单的方法将一个变量与多个值进行比较?


In PHP, is there a short way to compare a variable to multiple values?

基本上我想知道是否有一种方法来缩短这样的东西:

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

,这样就可以对变量进行测试或与多个值进行比较,而不必每次都重复变量和操作符。

例如,下面的内容可能会有所帮助:

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

或任何可以减少输入的内容

我用的是in_array()

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

不需要构造数组:

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

当然,从技术上讲,如果变量是twothr,这将返回true,因此添加"分隔符"可能很方便:

if (stristr('one/two/three', $variable))//or comma's or somehting else
$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";        
}

带开关箱

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

使用preg_grep可以比使用in_array更短更灵活:

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

因为可选的i模式修饰符(insensitive)可以匹配大写字母和小写字母