A simple way to check if a 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 an easier (i.e. shorter) way to write down two conditions?

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

+47
php if-statement condition conditional-statements
Nov 13 '13 at 9:23
source share
5 answers

For your first code, you can use a slight change to the answer given by @ShankarDamodaran using in_array in_array() :

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

or even shorter with the available notation [] starting with php 5.4 as pointed out by @Forty in the comments

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

such as:

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

... but shorter. Especially if you are comparing more than just "UK" and "B". I do not use an additional variable (Shankar used $ os), but instead I define an array in the if statement. Some may find it dirty, I find it quick and neat: D

The problem with your second code is that it can easily be replaced simply with TRUE, because:

 if (true) { 

equals

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

You ask if the string value is not A or Not B. If it is A, it is definitely not also B, and if it is B, then it is definitely not A. And if it is C or literally something else, it is also not A and not B. So this statement always (without SchrΓΆdinger's law here) returns the truth.

+93
Nov 13 '13 at 9:59
source share

You can use in_array() in PHP.

 $os = array("uk", "us"); // You can set multiple check conditions here if (in_array("uk", $os)) //Founds a match ! { echo "Got you"; } 
+15
Nov 13 '13 at 9:25
source share

If you plan to create a function in an if statement, I would also recommend using in_array. It is much cleaner.

If you are trying to assign values ​​to variables, you can use the shorthand if / else:

 $variable_to_fill = $some_variable !== 'uk' ? false : true; 
+1
Nov 13 '13 at 9:33
source share

You need to check multiple values. Try using the following code:

 <?php $illstack=array(...............); $val=array('uk','bn','in'); if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack} ?> 
+1
May 10 '16 at 8:29
source share

Some basic regex would be nice $some_variable !== 'uk' && $some_variable !== 'in': for $some_variable !== 'uk' && $some_variable !== 'in':

 if(!preg_match('/^uk|in$/', $some_variable)) { // Do something } 
0
Sep 20 '18 at 21:35
source share



All Articles