I am messing with PHP operators and I cannot understand why
10 & 10 == 10
returns 0. This should compare 10 to 10 which is true right?
The comparison operators have higher precedence than the bitwise operators, so that expression is evaluated as:
10 & (10 == 10)
10 == 10
evaluates to true, so you get 10 & true
.
The bitwise &
converts the true
to 1
, so you get 10 & 1
which is 0
.
Notice that 11 & 10 == 10
results in 1
, since 11 & 1 === 1
.
Because the ==
operator is parsed before the &
operator because it is judged more important by the parser. But you can override the default operator evaluation order with brackets:
(10 & 10) == 10
Your expression is similar to:
( 10 & 10 == 10 ) = ( 10 & (10 == 10) ) = ( 10 & (true) ) = 0
Precedence of ==
is from right (higher) it will be evaluated before &
& is used for bit operations and == for comparison so be careful ... Here is an example :
echo((10 & 12));
Is printing 8 because 10 = 00001010 and 12 = 00001100 and 00001010 & 00001100 = 00001000 = 8
Are you comparing if 10 is the same as 10?
IF (10 == 10) {
// condition code
}
or 10 and 10 are both true
IF (10 && 10) {
// condition code
}
& is the bitwise operator in php and == tests for equality.
Since the precedence, see http://php.net/manual/en/language.operators.precedence.php , of == is higher than &, your test is the same as 10 & (10 == 10)
10 == 10 will return boolean true (same as a 1 in binary)
Now we are left with 10 & true which is the same as 10 & 1
the bitwise operator, &, looks at each bit of the 2 values and sets the corresponding bit in the result to 1 if they are both 1 and 0 otherwise, eg:
5 (101) & 3 (011) = 1 (001)
5 (101) & 2 (010) = 0 (000)
6 (110) & 4 (100) = 4 (100)
Therefore 10 (1010) & 1 (0001) = 0 (0000) so the result of 10 & 10 == 10 is 0!
If you just want to compare 10 to 10 then use 10 == 10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.