3

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!

0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks, but in my head it was in two different cases : site1 or site4. And with && the two conditions must be executed. But it works thanks for your explanation.
4

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

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

This simplifies it if there are a lot of numbers to check against. This is even simpler in PHP 5.4+

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

1 Comment

It is also a good trick. Help a lot if many values needed to be checked. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.