|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-08-13 00:17 UTC] cattyv10 at gmail dot com
Description:
------------
Strange behaviour with bitwise AND when used in if statements.
Test script:
---------------
<?php
if(1&1 == 1&1) { echo "equal\n"; }else{ echo "not equal\n"; } //equal 0001 & 0001
if(1&3 == 1&3) { echo "equal\n"; }else{ echo "not equal\n"; } //not equal???? 0001 & 0011
if(2&2 == 2&2) { echo "equal\n"; }else{ echo "not equal\n"; } //not equal???? 0010 & 0010
?>
Expected result:
----------------
equal
equal
equal
Actual result:
--------------
equal
not equal
not equal
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 08 04:00:01 2026 UTC |
== has higher precedence than & so you're effectively writing if( (1) & (1 == 1) & (1) ) { // 1&true&1 -> 1&1&1 -> 1&1 -> 1 -> true if( (1) & (3 == 1) & (1) ) { // 1&false&1 -> 1&0&1 -> 0&1 -> 0 -> false if( (2) & (2 == 2) & (2) ) { // 2&true&2 -> 2&1&2 -> 0&2 -> 0 -> false http://php.net/manual/en/language.operators.precedence.php Use parentheses.