PHP - Operator Bitwise Operators

Introduction

PHP's bitwise operators work on the individual bits within integer variables.

Consider the integer value 1234.

Here's how those two bytes look as a string of bits:

00000100 11010010

PHP's bitwise operators let you manipulate these bits directly.

Operator
Description
Example
& (And)

Only bits set in both values
are set in the result
14 & 3 = 2
00001110 & 00000011 = 00000010
| (Or)

Bits set in either value are set
in the result
14 | 3 = 15
00001110 | 00000011 = 00001111
^ (Xor)

Bits set in either value (but
not both) are set in the result
14 ^ 3 = 13
00001110 | 00000011 = 00001101
~ (Not)


Bits set in the value are not set
in the result, and vice versa

~14 = -15
~00000000000000000000000000001110
= 11111111111111111111111111110001
<< (Shift left)

Shifts all bits in the first value
a number of places to the left
3 << 2 = 12
00000011 << 2 = 00001100
>> (Shift right)

Shifts all bits in the first value
a number of places to the right
8 >> 2 = 2
00001000 >> 2 = 00000010

~ (Not) inverts all the bits in the number.