What is the ~ (useful) operator in PHP?

20

What is the ~ (useful) operator in PHP?

I have seen things like:

echo ~PHP_INT_MAX

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

Example:

echo ~2; //Imprime -3

echo ~5; //Imprime -6
    
asked by anonymous 03.08.2015 / 17:12

1 answer

21

It is the negation operator bit a bit . That is, it inverts the value of all the bits of the given data. Those who were 0 saw 1 and those who were 1 saw 0. His name is bitwise not . Do not confuse with the negation logic operator ! .

It does not negate the number, so there is the unary operator of negative.

Then the number 2 can be represented in binary by

00000010 //isto é 2 em binário

negating (inverting) the bits is:

11111101 //isto é -3 em binário

I made 8 bits to simplify, probably the number would have bits . If you convert this number to decimal, you get the number of -3.

If you analyze, 2 is the third number of positives, and 3 is also the third number of negatives. There is a reversal in this sense, but going from the positive to the negative is a matter of the data type.

Its usefulness is pretty good in some scenarios, but most programmers can not see when it can be used to avoid miraculous math. The simple is often harder to see.

When you see this:

E_ALL & ~E_STRICT & ~E_WARNING & ~E_NOTICE

It reads like this: it binds all ALL errors, but NOT any errors that are STRICT, NOT WARNING, and NOTICE them. This is an expression that will result in a number that will be used properly by PHP to understand what is attached or not. The human understands the way I have shown, but to select, the code will treat the existing bits in appropriate combination.

Documentation .

    
03.08.2015 / 17:21