PHP Conditions – How to Properly Reverse an If Statement with Two Conditions

conditionsPHP

In PHP I have this if statement ( $first and $second will evaluate to true or false):

if ($first && $second) {
    // evereything is OK
} else {
    throw new Exception()...
}

My real code is much more complicated, I am trying to make simple example here.

I want to turn this if/else into one if with negation like this:

if (!($first && $second)){
    throw new Exception()...
}

// everything is OK

As you can see in this example, I've put ! negation sign in front of parentheses. Is this correct ? Do I need to negate every condition itself like this:

if (!$first && !$second)

Or I should use || operator:

if (!$first || !$second) // I am using OR here

I am not sure how these conditions are going to evaluate at the end, and I am confused by my dummy testing results. I really hope that someone can explain to me how all these checks are going to evaluate at the end.

Thanks to everyone who answered my question. Due to my low rep, I can not up-vote or pick some answer as the right one. You are all good for me 🙂

Best Answer

Build a truth table:

p  q    p && q    p || q    !(p && q)    !p || !q    !(p || q)   !p && !q
==========================================================================
0  0    0         0         1            1           1           1
0  1    0         1         1            1           0           0
1  0    0         1         1            1           0           0
1  1    1         1         0            0           0           0

Thus, you see that !(p && q) is equivalent to !p || !q, but not equivalent to !p && !q. You see that !(p && q) and !p || !q are the opposite of p && q.

Note that !(p && q) and !p || !q are equivalent and can be proved by using the De Morgan's laws.

Related Topic