phpoperatorsbit-manipulationtilde

What's the function of the ~ bitwise operator (Tilde)


Can someone explain me the ~ operator in PHP? I know it's a NOT-operator, but why does PHP convert following statement to the negative value of the variable minus one?

$a = 1; echo ~$a    // echo -2
$a = 2; echo ~$a    // echo -3
$a = 3; echo ~$a    // echo -4  

Solution

  • This is called the two's complement arithmetic. You can read about it in more detail here.

    The operator ~ is a binary negation operator (as opposed to boolean negation), and being that, it inverses all the bits of its operand. The result is a negative number in two's complement arithmetic.