What is the ~ (tilde) operator in PHP for?


What is the ~ (tilde) operator in PHP for?

I've seen things like:


Until then I thought it was to "invert" a number to negative, or something like that, but with the tests I saw that I was wrong.


echo ~2; //Imprime -3

echo ~5; //Imprime -6


It is the bitwise negation operator . That is, it reverses the value of all bits of the data in question. Those that were 0 became 1 and those that were 1 became 0. Its name is bitwise not . Not to be confused with the logical negation operator ! .

It does not negative the number, for this there is the unary negative operator.

Then the number 2 can be represented in binary by

00000010 //isto é 2 em binário

negating (reversing) the bits becomes:

11111101 //isto é -3 em binário

I made it with 8 bits for simplicity, probably the number would have more bits . If you convert this number to decimal, you will get -3.

If you analyze, the 2 is the third number of the positive ones, and the 3 is also the third number of the negative ones. There is an inversion in this sense, but the fact of going from positive to negative is a question of the type of data.

Its usefulness is quite great in some scenarios, but most programmers can't see when it can be used to avoid fancy math. Simple is often harder to see.

When you see this:


It reads like this: it turns on all errors ALL, but NOT the errors that are STRICT , also NOT the WARNING and also NOT the NOTICE . This is an expression that will result in a number that will be properly used by PHP to understand what is on and what is not. The human understands the way I've shown, but to select, the code will handle the existing bits in proper combination.

Documentation .

Scroll to Top