简写如下:if($variable == 1 || $variable == "whatever"|


Short hand to do something like: if($variable == 1 || $variable == "whatever" || $variable == '492') .

我发现我自己在做这种类型的IF语句分配。例如:

if($variable == 1 || $variable == "whatever" || $variable == '492') { ... }  

除了时间分配,我将$变量与4-5个东西进行比较,有时更多。有没有更简单的写法?您可以看到,重复$variable ==会变得冗余。

我希望这能工作,但它没有:

if($variable == (1 || "whatever" || 492) { ... }

您可以使用这种简写,但请记住,使用or子句显式列出它们的效率较低:

if(in_array($variable, array(1, 'whatever', '492'))){ ... }

如果您想使用===而不是==,则等效为:

if(in_array($variable, array(1, 'whatever', '492'), TRUE)){ ... }

if(in_array($variable, array(1, "whatever", 492)))

in_array(…)。http://php.net/manual/en/function.in-array.php

虽然这不能直接回答问题,但我认为值得添加这个方法作为解决上述问题的一部分:

如果你发现某项有多个值,你可能会发现下面的内容是合适的:

if (true === is_condition_one ( $variable )) {
  // Execute any condition_one logic here
}
function is_condition_one ( $variable = null ) {
  $arrKnownConditions = array (
    // This can be an array from the database
    // An array from a file
    // An array from any other source
    // or an array of hardcoded values
  );
  return in_array ( $variable, $arrKnownConditions );
}

我同意Godwin、toon81和PaulPRO的观点,但我觉得如果你经常这样做,你可能会从重构中受益,因为重构是你解决方案的一部分。上面的重构可以帮助你更好地组织这个项目和其他项目,通过定义比较的目的,让你的代码更具可读性,并将那些硬编码的值抽象到一个函数中。这可能还会帮助您在代码的其他部分更有信心地重用该签入。

另一个可行的替代方法是使用正则表达式。

if (preg_match('^1|whatever|492$', $variable)) { ... }

2023年的答案

在新的php更新中,您还可以使用您建议的方法

$variable = "492" ;
if($variable  == 1 || "whatever" || '492'){
    echo "true";
}

另一个例子
if($testvar =! 0 && ($variable  == 1 || "whatever" || '492')){
    echo "true";
}