Skip to main content
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.

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

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.

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.

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.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More