its_me its_me - 6 months ago 26
PHP Question

Simpler way to check if variable is not equal to multiple string values?

Current Codes:

<?php

// See the AND operator; How do I simplify/shorten this line?
if( $some_variable !== 'uk' && $some_variable !== 'in' ) {

// Do something

}

?>


And:

<?php

// See the OR operator; How do I simplify/shorten this line?
if( $some_variable !== 'uk' || $some_variable !== 'in' ) {

// Do something else

}

?>


Is there a simpler (i.e. shorter) way to write the two conditions?

NOTE: Yes, they are different, and I am expecting different ways to shorten the codes.

Answer

For your first code, you can use a short alteration of the Shankar Damodaran's answer using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

Comments