-8

What is the difference between

if ($check)
if (!$check)
if (!!$check) 

and Why?

Qirel
  • 25,449
  • 7
  • 45
  • 62
Jasmin
  • 21
  • 7
  • You can find the difference by debugging : – hs-dev2 MR Jul 11 '19 at 04:38
  • 1
    I get it guys, he could find the answer from debugging and maybe he should (to learn!) but that doesn't record the difference here for others later on. Maybe its instructional to know the differences between the 3 variations for reference purposes. I think he has a valid question and the answer would helpful to others later on. If the OP does figure out I'd like to remind him he can answer his own question below. – Jeff Mergler Jul 11 '19 at 05:53

1 Answers1

1

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).

Qirel
  • 25,449
  • 7
  • 45
  • 62