What is the
~ (tilde) operator for in PHP?
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 denial of bitwise. That is, it inverts 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.
So the number 2 can be represented in binary by
00000010 //isto é 2 em binário
denying (inverting) the bits is:
11111101 //isto é -3 em binário
I made it with 8 bits for simplicity, the number would probably have more bits . If you change this number to decimal, you will get the -3.
If you look at it, the 2 is the third number of the positives, and the 3 is also the third number of the negatives. There is a reversal in this regard, but going from positive to negative is a matter of data type.
Its usefulness is quite great in some scenarios, but most programmers cannot see when it can be used to avoid fancy math. The simple is often more difficult to see.
When you see this:
E_ALL & ~E_STRICT & ~E_WARNING & ~E_NOTICE
It reads like this: turns on all ALL errors, but NOT
STRICT errors, also NOT
WARNING and NOT
NOTICE . This is an expression that will result in a number that will be properly used by PHP to understand what is on and off. The human understands the way I showed, but to select, the code will deal with the existing bits in proper combination.