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



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

发现我可以用类似 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
}

最新更新