← Back to PHP Course | Chapter 3: Operators | Lesson 4 of 8

PHP Bitwise Operators

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
<?php
echo 6 & 3, "\n"; // AND
echo 6 | 3;       // OR
?>

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
<?php
echo 6 ^ 3;
?>

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
<?php
echo ~5;
?>

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
<?php
echo 4 << 1, "\n"; // multiply by 2
echo 4 >> 1;       // divide by 2
?>

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
<?php
define('READ_FLAG', 1);
define('WRITE_FLAG', 2);
$permissions = READ_FLAG | WRITE_FLAG;
var_dump((bool)($permissions & READ_FLAG));
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.