PHP Bitwise Operators
In this page:
$result = $a & $b; // AND
$result = $a | $b; // OR
$result = $a ^ $b; // XOR
$result = ~$a; // NOT (flip every bit)
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
// Print `6 ^ 3` to the output
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
// Print `~5` to the output
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
// Call `define('READ_FLAG', 1)`
define('READ_FLAG', 1);
// Call `define('WRITE_FLAG', 2)`
define('WRITE_FLAG', 2);
// Declare `$permissions`, set to `READ_FLAG | WRITE_FLAG`
$permissions = READ_FLAG | WRITE_FLAG;
// Print a detailed dump (with types) of `(bool)($permissions & READ_FLAG)`
var_dump((bool)($permissions & READ_FLAG));
?>
Login to try C/C++/Java/PHP code in the editor
- Confusing
&(bitwise AND) with&&(logical AND), so5 & 2gives0instead of a boolean. - Being surprised that
~5is-6, because PHP integers are signed and~flips every bit including the sign bit. - Shifting by a negative amount, which throws an
ArithmeticErrorin PHP 7 and later.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: