Multiple ORs in php if () don't seem to respond properly. The tested array values ​​and that’s it. What am I doing wrong?

I have a very simple if statement that works perfectly until I add two more || (or) operators.

Here is my code:

if ($planDetails['Company']['name'] != 'company1' || $planDetails['PlanDetail']['name'] != 'pd-name1' || $planDetails['PlanDetail']['name'] != 'pd-name2') { echo "TEST"; } 

I checked the array and table data to make sure they are exact in the names, etc. . And it doesn’t kick. What am I doing wrong? When I remove the extra 2 || parameters, the first argument works fine, so I know that my logic is correct.

What am I doing wrong here. Someone please put me straight!

+4
source share
3 answers

Your hordes should be u. The expression a != 1 || a != 2 a != 1 || a != 2 always true because, regardless of the value of a, one or the other of the expressions will be true, so the final result will be true.

To fix, change || at && .

I assume that you made this mistake because you started with this expression and wanted to invert it:

 if ($planDetails['Company']['name'] == 'company1' || $planDetails['PlanDetail']['name'] == 'pd-name1' || $planDetails['PlanDetail']['name'] == 'pd-name2') 

The easiest way to invert the following expressions:

 if (!($planDetails['Company']['name'] == 'company1' || $planDetails['PlanDetail']['name'] == 'pd-name1' || $planDetails['PlanDetail']['name'] == 'pd-name2')) 

Using this method, you don’t need to do any complicated logic in your head to see that it works - it’s just a denial of what you already know. Note that this is not the same as inverting == to != Individually. See De Morgan Laws for more details.

+6
source

What I read here:

 If $variable is not equal to A Or $variable is not equal to B Then echo "TEST" 

Since $variable cannot equal both A and B at the same time, it will always print "TEST".

Of course, the above applies to the last two conditions of your if .

+7
source

Refer to De Morgan Laws .

 NOT (P AND Q) = (NOT P) OR (NOT Q) NOT (P OR Q) = (NOT P) AND (NOT Q) 

You have:

 (NOT P) OR (NOT Q) OR (NOT R) 

This is the same as:

 NOT (P AND Q) OR (NOT R) => NOT (P AND Q AND R) 

Therefore, P, Q, R must be false to print "TEST". If one of them is true , you will not print "TEST".

I believe you want:

 NOT (P OR Q OR R) 

What will happen:

 (NOT P) AND (NOT Q) AND (NOT R) 

OR

 if (!($planDetails['Company']['name'] == 'company1' || $planDetails['PlanDetail']['name'] == 'pd-name1' || $planDetails['PlanDetail']['name'] == 'pd-name2')) { echo "TEST"; } 

ELSE

 if ($planDetails['Company']['name'] != 'company1' && $planDetails['PlanDetail']['name'] != 'pd-name1' && $planDetails['PlanDetail']['name'] != 'pd-name2') { echo "TEST"; } 
+6
source

Source: https://habr.com/ru/post/1342353/


All Articles