PHP NOT (!) operator is one of the logical operators that To demonstrate the opposite of true or false value according to the operand result.

The PHP NOT operator is also written as a “NOT“ keyword OR “!” in the condition block. Let’s take an example.

<?php
  $is_correct = ! false;
  var_dump( $is_correct ); // bool(true)
?>

The condition block means the $is_correct takes a false boolean value, and the NOT operator check if this variable is taking positive action.

So the PHP NOT (!) operator performs the opposite of the current value.

<?php
  $username = NULL;
  if ( ! $username ) {
    echo "The username doesn't exists !";
  } 
?>

In the previous example, the $username takes a null value, but the NOT operator is logical, so what happened there?

Before explaining that, you have to understand the PHP type juggling.

Anyway, in the previous example, we have a juggling case. The NOT (!) operator would produce a true or false value. But in the $username we have another special data type with a NULL value. So PHP automatically converted the $username data type value to a boolean data type.

See what is happening behind the scene in PHP juggling.

if ( ! $username ) ... this has to be in the backend as this (! (bool) $username). So two boolean values are compared together. The first one is false, and the second one is false also, so the result is true.

PHP NOT Operator Accepts More than Operand

The PHP NOT operator accepts more than operand in the condition. Let’s see that.

<?php
  $inline = 10 > 11; // false
  var_dump( ! $inline ); // bool(true)
  var_dump( ! 10 > 11 ); // bool(false) => more than operand 
?>

In the first line, the $inline variable did a priority. So the first two statements are executed like the following steps.

  1. The $inline variable produced the false boolean value.
  2. It sent the false value into the var dump function.
  3. The NOT operator means a false value.
  4. The final comparison is false, is false, so the result was true.

But in the last line, it made a priority for the NOT operator, and here the PHP type juggling was executed, so it executed the statements like in the following steps.

  1. The number 10 is not negative, it is a positive integer value. And the priority was for NOT operator So it started like this ! 10 and the result for this was false.
  2. So is false NOT ( bool ) 11 it gave us the bool(false).

That’s all, thank you for reading.