PHP Bitwise Operators
In this page:
Bitwise AND and OR
Bitwise operators work on a number's individual binary digits rather than its overall value. & sets each output bit to 1 only where *both* input bits were 1; | sets each output bit to 1 where *either* input bit was 1 — the same logic as &&/||, just applied bit by bit instead of to whole booleans.
Example: Bitwise AND and OR
<?php
echo 6 & 3, "\n"; // AND
echo 6 | 3; // OR
?>
Login to try C/C++/Java/PHP code in the editor
Bitwise XOR (^)
^ (XOR) sets each bit to 1 exactly where the two inputs disagree — one is 1 and the other is 0. Where the bits match, whether both 0 or both 1, the result bit is 0. This bit-by-bit 'exactly one' behavior is what makes XOR useful for toggling flags on and off.
Example: Bitwise XOR (^)
<?php
echo 6 ^ 3;
?>
Login to try C/C++/Java/PHP code in the editor
Bitwise NOT (~)
~ flips every bit of a number in one operation, turning every 1 into a 0 and every 0 into a 1. Because of how negative numbers are represented in binary (two's complement), this ends up mathematically equivalent to -(x + 1) — a detail that trips people up until they've traced through an example.
Example: Bitwise NOT (~)
<?php
echo ~5;
?>
Login to try C/C++/Java/PHP code in the editor
Shift Operators (<<, >>)
<< shifts a number's bits left, filling the vacated positions on the right with zeros — the same effect as multiplying by a power of two. >> shifts bits right, which has the effect of dividing by a power of two and discarding any remainder, making both useful as very fast alternatives to multiplication or division by 2.
Example: Shift Operators (<<, >>)
<?php
echo 4 << 1, "\n"; // multiply by 2
echo 4 >> 1; // divide by 2
?>
Login to try C/C++/Java/PHP code in the editor
Bitwise Flags Usage
A common real use is packing several independent yes/no flags into one integer, each represented by a single bit — checking $permissions & READ_FLAG tells you if that one flag is set, without needing a separate variable for every flag.
Example: Bitwise Flags Usage
<?php
define('READ_FLAG', 1);
define('WRITE_FLAG', 2);
$permissions = READ_FLAG | WRITE_FLAG;
var_dump((bool)($permissions & READ_FLAG));
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: