PHP comparison with multiple conditions

Is it correct to write it?

 if($site!=1 || $site!=4)

      

I want to execute code if site id is not 1 or 4. Possible two negatives with OR? Because it doesn't work.

Thank!

+3


source to share


2 answers


When you use ||

, if any of them satisfies, it will be executed. When you don't want both of them satisfied, you need to use &&

. Should be -

if($site!=1 && $site!=4)

      

It will check both conditions, i.e. $site

not equal 1

or 4

.



OR you can use in_array

-

if(!in_array($site, array(1, 4)))

      

It currently checks $site

for 1

or not first if it will not enter the state and ignore the rest of the conditions. Therefore, 4

it will not be checked for.

+6


source


Although you already have the correct answer, you can also use

if (!in_array($site,array(1,4)))

      



This makes it easier if there are many numbers to check. It's even easier in PHP 5.4+

if (!in_array($site,[1,4]))

      

+4


source







All Articles