Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

PHP bitwise operators

Reference for PHP bitwise operators &, |, ^, ~, << and >>: flags and masks, shifts, string operands, 64-bit behavior and common mistakes.

Bitwise operators work on the individual bits of integers. & (and), | (or), ^ (xor) and ~ (not) combine or flip bits, and << and >> shift them left or right. They are the tool of choice for flag sets, masks and compact binary formats.

On 64-bit PHP, integers have 64 bits and are signed, so ~ and large shifts can give negative results. Do not confuse these operators with the logical && and ||, which work on truth values.

PHP
echo 0b1100 & 0b1010;  // 8   (0b1000)
echo 1 << 4;           // 16

Try it

PHP Combining, masking and shifting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Permission flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
$a & $b    $a | $b    $a ^ $b    ~$a    $a << $n    $a >> $n
Operator Name Result
$a & $b And Bits set in both
$a | $b Or Bits set in either
$a ^ $b Xor Bits set in exactly one
~$a Not All bits flipped
$a << $n Shift left Shifts $n bits left (multiplies by 2 per bit, may overflow)
$a >> $n Shift right Shifts $n bits right, keeping the sign (arithmetic shift)

Errors: a negative shift count throws ArithmeticError. Shifting by 64 or more bits gives 0 (or -1 for a negative value with >>).

Usage notes

  • Precedence is low. $flags & MASK === 0 is parsed as $flags & (MASK === 0). Always parenthesize: ($flags & MASK) === 0. See operator precedence.
  • Operands are integers. Floats and numeric strings are converted to int first; a fractional part is dropped (and a float with a fractional part is deprecated in implicit conversion since PHP 8.1).
  • Strings are different. If both operands of &, | or ^ are strings, the operation runs on the bytes of each character. ~ also works on one string. This is rarely wanted; cast with (int) if you meant numbers.
  • Right shift is arithmetic. Negative numbers stay negative: -8 >> 1 is -4.
  • Compound forms: &=, |=, ^=, <<= and >>= exist. $x &= ~FLAG clears a flag.
  • Typical uses: permission and option flags (E_ALL & ~E_NOTICE), packing values, checking odd/even with $n & 1, power-of-two tests with ($n & ($n - 1)) === 0.
  • Format with decbin()/printf("%b") to see the bits, and write bit literals as 0b1010.