Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ! (Logical NOT) operator is a unary operator that negates the boolean value of a given expression. It evaluates the operand, implicitly casts it to a boolean if necessary, and returns the inverse boolean value: true becomes false, and false becomes true.
!$expression

Mechanics and Type Juggling

Because PHP is a dynamically typed language, the ! operator relies on PHP’s internal type juggling rules. Before negation occurs, the operand is evaluated for its boolean equivalent (truthiness). If the operand evaluates to a falsy value, the ! operator returns true. If the operand evaluates to a truthy value, it returns false. The following values are strictly evaluated as falsy in PHP, meaning the ! operator will return true when applied to them:
  • The boolean false
  • The integer 0
  • The float 0.0
  • The empty string "" and the string "0"
  • An empty array []
  • The special type null
// Strict boolean negation
var_dump(!true);      // bool(false)
var_dump(!false);     // bool(true)

// Implicit boolean casting (Type Juggling)
var_dump(!0);         // bool(true)  - 0 is falsy
var_dump(!1);         // bool(false) - 1 is truthy
var_dump(!"");        // bool(true)  - empty string is falsy
var_dump(!"0");       // bool(true)  - string "0" is falsy
var_dump(!"PHP");     // bool(false) - non-empty string is truthy
var_dump(![]);        // bool(true)  - empty array is falsy
var_dump(![1, 2]);    // bool(false) - populated array is truthy
var_dump(!null);      // bool(true)  - null is falsy

Operator Precedence and Associativity

The ! operator is right-associative and possesses a high operator precedence. It binds tighter than comparison operators (e.g., ==, ===, <, >) and binary logical operators (e.g., &&, ||, and, or). Because of this high precedence, the ! operator will evaluate its immediate right-hand operand before subsequent comparisons occur, which often necessitates the use of parentheses to achieve the desired evaluation order.
$a = true;
$b = false;

// Evaluates as (!true) == false -> false == false -> true
var_dump(!$a == $b); 

// Evaluates as !(true == false) -> !(false) -> true
var_dump(!($a == $b));

Double Negation (!!)

Applying the Logical NOT operator twice sequentially (!!) acts as an implicit boolean cast. The first ! coerces the operand to a boolean and inverts it; the second ! inverts it back, effectively returning the strict boolean representation of the original value. This is functionally identical to using the (bool) cast.
var_dump(!!"PHP"); // bool(true)
var_dump(!!0);     // bool(false)
Master PHP with Deep Grasping Methodology!Learn More