What is the difference between
if ($check)
if (!$check)
if (!!$check)
and Why?
What is the difference between
if ($check)
if (!$check)
if (!!$check)
and Why?
In the end, both
if ($check)
and
if (!!$check)
ends up checking if $cond
is a truthy value.
As you may well know, the !
operator is the not
operator. So !true
becomes false
. When you do !false
, it becomes true! When doing !!
(which is the not-operator applied twice, nothing more), think of it like !(!true)
, which ends up back at true ("not not true").
This is trivial for booleans, but what about other values? In PHP, you can put any value as the condition for an if
statement. There are a lot of values that are "truthy", meaning that they will result to true
if put in a condition. So what happens, exactly?
Here we apply the not-operator !
twice to different values to see what we get.
# Test // Description -- result
# -----------------------------------------------------------------
var_dump(!![]); // Empty array -- boolean false
var_dump(!![48]); // Non-empty array -- boolean true
var_dump(!!0); // Zero -- boolean false
var_dump(!!38); // Non-zero -- boolean true
var_dump(!!""); // Empty string -- boolean false
var_dump(!!"foo"); // Non-empty string -- boolean true
var_dump(!!(new stdClass())); // Empty object -- boolean true
var_dump(!!null); // null -- boolean false
As you can see from the above results, it will typecast the value to a boolean, which will do the same as doing
if ((bool)$check)
In the end, doing either if ((bool)$check)
, if (!!$check)
or if ($check)
will all result in the same outcome - the condition will be true for a truthy value. The difference ends up being what is evaluated where. The two first sends a boolean as the condition, the last sends the value itself and checks for a truthy value in the condition.
As for the if (!$check)
, that's just the not-operator applied once, which would invert it and cast to a boolean (so any "falsy" value becomes true, and any "truthy" value becomes false).