Skip to content

How to Use the Double Not(!!) Operator in PHP

Maybe you have already met the double NOT (!!) or the NOT NOT operator while working in PHP.

Here, we will explain how it is used with the help of several examples.

Using the Double NOT (!!) Operator

This PHP operator is aimed at returning the boolean value of an expression or a variable. To be more explicit: the first NOT operator (!) will negate the expression, and the second one (!) will negate the first result, bringing back the initial boolean value. In PHP, !! is essentially a shorthand for explicit boolean casting (bool).

The double NOT (!!) operator can be used to improve code readability and guarantee that the result is of the Boolean data type.

For a better understanding, check out the example below:

PHP using the double NOT (!!) operator

php
<?php

// Declaring a variable
// and initializing it
$a = 1;

// Using double not operator
$a = !!$a;

// Displaying the value
// of variable a.
echo $a;

?>

How the NOT (!) and Double NOT (!!) Operators Differ from Each Other

The NOT (!) operator is aimed at negating the Boolean value of the concerned data. For instance, if the value of $a is true, then applying the NOT operator to it (!$a) will make it false. In contrast, the double NOT (!!) operator returns true for truthy values and false for falsy values.

Let’s see another example:

PHP example of double NOT (!!) operator

php
<?php

// PHP program to demonstrate
// Double NOT operator

// Declaring a variable and
// initializing it
$t = 10;

// Checking condition
if ($t !== 10) {
  echo "This is NOT operator!";
} elseif (!!$t) {
  echo "This is Double NOT operator!";
} else {
  echo "Finish!";
}

?>

The example above demonstrates that !! preserves the truthiness of the variable and explicitly casts it to a Boolean value.

Dual-run preview — compare with live Symfony routes.