Search code examples
phpcomparisonlogiccomparison-operators

PHP Comparisons with multiple conditions


Is it right to write this ?

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

I want to execute a code if the site ID isn't 1 or 4. Two negations are possible with a OR? Because it doesn't work.

Thanks!


Solution

  • When you using || if any of them satisfies it will be executed. When you dont want the both should be satisfied the you need to use &&. Should be -

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

    It will check the both conditions, i.e. $site is not equals to 1 or 4.

    OR you can use in_array -

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

    Currently it will check $site is 1 or not first, if it is not it will go inside the condition and ignore the rest of the conditions. So for 4 it will not be checked.