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 ~ (tilde) operator in PHP is the bitwise NOT operator. It is a unary operator that performs logical negation on each individual bit of its operand, flipping every 0 to 1 and every 1 to 0 at the binary level.
$result = ~$operand;

Behavior with Integers

When applied to an integer, the ~ operator evaluates the value using the system’s native signed integer representation (typically 64-bit Two’s Complement). Because the sign bit is also inverted, applying the bitwise NOT operator to an integer x mathematically yields -(x + 1).
$x = 5; 
// 64-bit binary: 00000000...00000101

$y = ~$x; 
// 64-bit binary: 11111111...11111010 (Two's complement for -6)

var_dump($y); // int(-6)

Behavior with Strings

Unlike many strictly typed languages, PHP allows bitwise operations directly on strings. When the ~ operator is applied to a string, it iterates through the string and performs a bitwise NOT operation on the underlying byte (ASCII) value of every single character. The length of the resulting string is identical to the length of the original string.
$char = 'a'; 
// ASCII 97, Binary: 01100001

$inverted = ~$char; 
// Binary: 10011110, ASCII 158 (Extended ASCII)

var_dump(bin2hex($inverted)); // string(2) "9e"

Implicit Type Casting and Type Errors

If the operand is a float, a boolean, or the special null type, PHP implicitly casts the value to an integer before applying the bitwise inversion. However, applying the ~ operator to non-scalar types like arrays or objects is invalid and will throw a TypeError.
// Floats are truncated to integers before inversion.
// Note: Since PHP 8.1, implicitly converting a float with a fractional 
// part to an integer emits a deprecation warning.
$float = 2.9; 
var_dump(~$float); 
// Deprecated: Implicit conversion from float 2.9 to int loses precision
// int(-3)

// Booleans are cast to 1 or 0
$boolTrue = true; // Cast to int(1)
var_dump(~$boolTrue); // int(-2)

$boolFalse = false; // Cast to int(0)
var_dump(~$boolFalse); // int(-1)

// Null is cast to 0
$nullVal = null; // Cast to int(0)
var_dump(~$nullVal); // int(-1)

// Arrays and Objects throw a TypeError
$arr = [];
var_dump(~$arr); 
// Fatal error: Uncaught TypeError: Cannot perform bitwise not on array

Operator Precedence

The ~ operator has very high precedence in PHP, evaluating before most arithmetic operators (+, -, *, /), bitwise shift operators (<<, >>), and logical operators. However, the exponentiation operator (**) has higher precedence than the unary ~ operator.
$val1 = ~2 + 3; 
// Evaluates as (~2) + 3 -> (-3) + 3 -> 0
// It does NOT evaluate as ~(2 + 3)

$val2 = ~2 ** 3;
// Evaluates as ~(2 ** 3) -> ~(8) -> -9
// It does NOT evaluate as (~2) ** 3 -> (-3) ** 3 -> -27
Master PHP with Deep Grasping Methodology!Learn More