替代in_array或if语句中的多个OR

时间:2012-08-24 15:50:48

标签: php optimization if-statement

所以,正如标题所说......任何替代方案:

$valid_times = array('ever', 'today', 'week', 'month');
if (($this->_time == 'ever') OR ($this->_time == 'day'))

OR

if (in_array($this->_time, $valid_times))

...

注意:我知道上面提到的工作,但我只是在寻找新的东西来学习和试验

更新

感谢您提供的信息,但我没有提到switch()作为替代方案,因为我的代码并非如此。它必须是一个if语句,我想知道是否存在类似的东西:

if($this->_time == (('ever') OR ('day') OR ('month')))
你怎么看?如果上面提到的话,这将是第一个更短的方式

7 个答案:

答案 0 :(得分:2)

[编辑]删除原始答案,因为您现在已指定不想使用switch

在您更新的问题中,您询问是否可以执行此类操作:

if($this->_time == (('ever') OR ('day') OR ('month')))

直接答案是'不,不是PHP'。你得到的最接近的是in_array(),数组值在同一行代码中就位了:

if(in_array($this->_time, array('ever','day','month'))

PHP 5.4有一个更新允许更短的数组语法,这意味着你可以删除单词array,这使它更具可读性:

if(in_array($this->_time, ['ever','day','month'])

但它仍然是in_array()电话。你无法解决这个问题。

答案 1 :(得分:2)

我能想到实现这一目标的唯一选择就是使用正则表达式。

$valid_times = array('ever','day','week','hour');

if(preg_match('/' . implode('|', $valid_times) . '/i', $this->_time)){
    // match found
} else {
    // match not found
}

答案 2 :(得分:2)

怎么样?

$a1 = array("one","two","three");
$found = "two";
$notFound = "four";

if (count(array_diff($a1,array($found))) != count($a1))
/* Found */

你可以使用

$found = array("one","three");

if (count(array_diff($a1,$found)) != count($a1));
/* Either one OR three */

http://codepad.org/FvXueJkE

答案 3 :(得分:1)

对于in_array有时会这样吗?

$arr = array(1, 2, 'test');
$myVar = 2;

function my_in_array($val, $arr){
    foreach($arr as $arrVal){
        if($arrVal == $val){
            return true;
        }
    }
    return false;
}

if(my_in_array($myVar, $arr)){
    echo 'Found!';
}

答案 4 :(得分:1)

康复,但它是另类

$input = 'day';
$validValues = array('ever','day');
$result = array_reduce($validValues,
                       function($retVal,$testValue) use($input) {
                           return $retVal || ($testValue == $input);
                       },
                       FALSE
                      );
var_dump($result);

答案 5 :(得分:0)

您也可以使用switch语句。

switch ($this->_time) {
  case 'ever':
  case 'day':
    //code
    break;
  default:
    //something else
}

答案 6 :(得分:0)

为了科学起见,事实证明您可以在三元运算符中使用yield,因此您可以在匿名生成器中放入一些复杂的求值,并将其产生于第一个求值为true的值,无需对它们全部进行评估:

$time = 'today';
if( (function()use($time){
    $time == 'ever' ? yield true:null;
    $time == 'today' ? yield true:null;
    $time == 't'.'o'.'d'.'a'.'y' ? yield true:null;
})()->current() ){
    echo 'valid';
}

在这种情况下,它将回显'valid'而无需评估连接。

相关问题