我们可以使用一个逻辑表达式来一次比较多个字符串吗?

Can we use one logic expression to compare multiple strings at once?

我试图找到一种更简单的方法来检查一个 var 是否不等于一个比较字符串中的多个值。

我发现我可以使用 empty() 之类的东西来减少代码,但不能使用 == 来减少字符串值。

empty() 例子来验证我的概念。

if (empty($var_1 . $var_2 . $var_3) { echo 'All these vars are empty, run code...'; }

以上检查 $var_1、$var_2 和 $var_3 是否为空。

但是在使用 !== 时有没有办法 运行 类似的东西?

查看下面的代码解释...

Test('unknown_value');
echo PHP_EOL;
Test('value_1');

function Test($var = '') {

    // Below method is ideal...

    // if ($var !== 'value_1' . 'value_2' . 'value_3') {

    // Below method is 2nd to ideal

    // if ($var !== 'value_1' and 'value_2' and 'value_3') {

    // But I have to write it like below...
    // I'm looking for a way to not have to write $var !== for each comparison since they will all be not equal to

    if ($var !== 'value_1' and $var !== 'value_2' and $var !== 'value_3') {

        echo 'Failed!!!';

    }

    elseif ($var == 'value_1' or $var == 'value_2' or $var == 'value_3') {

        echo 'Accessed!!!';

    }

}

使用in_array,像这样:

if (in_array(trim($someVariable), [ 'this', 'that', 'the other'] )) {
    // $someVariable is one of the elements in the array
}