Fearless Mode
Fearless Mode

Reputation: 241

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

I'm trying to find a simpler way to check that one var does not equal multiple values in one comparison string.

I found that I can reduce code with something like empty() but not with == for string values.

empty() example to validate my concept.

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

The above checks if $var_1, $var_2 and $var_3 are empty.

But is there a way to run something similar when using !== ?

See code explanation below...

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!!!';

    }

}

Upvotes: 1

Views: 43

Answers (1)

user2182349
user2182349

Reputation: 9782

Use in_array, like so:

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

Upvotes: 3

Related Questions