所以,正如标题所说。。。的任何替代方案
$valid_times = array('ever', 'today', 'week', 'month');
if (($this->_time == 'ever') OR ($this->_time == 'day'))
或
if (in_array($this->_time, $valid_times))
注意:我知道上面提到的有效,但我只是在寻找新的东西来学习和实验
更新
谢谢你提供的信息,但我没有提到switch()
作为替代方案,因为我的代码不是这样。它必须是一个if语句,我想知道是否存在类似于的东西
if($this->_time == (('ever') OR ('day') OR ('month')))
你觉得怎么样?如果上面提到
怎么样?
$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
我能想到的实现这一点的唯一替代方案是使用regex。
$valid_times = array('ever','day','week','hour');
if(preg_match('/' . implode('|', $valid_times) . '/i', $this->_time)){
// match found
} else {
// match not found
}
[EDIT]删除了原始答案,因为您现在已经指定不想使用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()
调用。你绕不过去。
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!';
}
卷积,但它是一种替代
$input = 'day';
$validValues = array('ever','day');
$result = array_reduce($validValues,
function($retVal,$testValue) use($input) {
return $retVal || ($testValue == $input);
},
FALSE
);
var_dump($result);
您也可以使用switch语句。
switch ($this->_time) {
case 'ever':
case 'day':
//code
break;
default:
//something else
}
为了科学起见,事实证明你可以在三元运算符中使用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'
。