Reputation: 11887
Let me share some PHP code with you:
$var1 = '';
$var2 = 0;
echo '<pre>';
var_dump($var1 == $var2); //prints bool(true)
echo '</pre>';
echo '<pre>';
var_dump($var1 != $var2); //prints bool(false)
echo '</pre>';
echo '<pre>';
var_dump(!$var1 == $var2); //prints bool(false)
echo '</pre>';
echo '---<br />';
echo '<pre>';
var_dump($var1 === $var2); //prints bool(false)
echo '</pre>';
echo '<pre>';
var_dump($var1 !== $var2); //prints bool(true)
echo '</pre>';
echo '<pre>';
var_dump(!$var1 === $var2); //prints bool(false) .. WTFF????
echo '</pre>';
Question is... why does that last statement (! $var1 === $var2)
NOT yield the same result as ($var !== $var2)
??? I mean, it's what we would expect, no?
I used to use both ways interchangeably but now I only use !==
although I still don't know why the other form does not work...
Upvotes: 0
Views: 163
Reputation: 21856
This is a matter of precedence:
The not operator is first applied to $var1
and results in a boolean true. And a boolean true is not exact equal to a int 0, so it evaluates to false.
Upvotes: 0
Reputation:
The last statement is evaluated as:
(!$var1) === $var2
Since $var1
is a falsey value (empty string), inverting it gives you a truthy value (1
), which is not equal (and certainly not identical!) to 0
. Thus, the comparison is false
.
(Note that I'm deliberately using the terms "truthy" and "falsey" here, as ''
and 0
are not quite true
and false
.)
Upvotes: 1
Reputation: 14681
!$var1
is TRUE
, $var2
is 0
.
They are not equal, so the result is false
.
Maybe you were confused with !($var1 === $var2)
Upvotes: 4