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 :)
!==
, IMO it's easier to read...if($user !== 'john' || $status !== 'active')
. Also, note the!==
vs. just!=
, this checks for strict equality.||
in that to make it properly exclude his conditions. He's using an and, so if either one doesn't match then it will fall to the else - the either makes the else an or, not an and.