Bitwise Operators and Flags

AND &, OR |, XOR ^, NOT ~, shifts << >>. The classic real-world use is compact permission flags.

Bitwise operators work on the individual bits of integers. They feel low-level, but they power a very practical pattern: packing many on/off options into a single integer.

OperatorNameExample
&AND6 & 3 = 2
|OR6 | 3 = 7
^XOR6 ^ 3 = 5
<<left shift1 << 3 = 8

Easy example

<?php
$flags = 0b0000;
$flags |= 0b0010;   // turn a bit ON
var_dump(($flags & 0b0010) !== 0); // is it ON? true

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Compact user permission flags (READ, WRITE, DELETE) into a single integer column using OR | combinations.
  • Check whether a specific permission bit is set using AND & without querying a permissions table.
  • Toggle a feature flag bit with XOR ^ in an admin panel that controls runtime feature switches.

More examples

Defining and combining flags

OR | combines bits: each permission occupies its own bit, so any set of permissions fits in a single integer.

Example · php
<?php
const PERM_READ   = 1;  // 001
const PERM_WRITE  = 2;  // 010
const PERM_DELETE = 4;  // 100

$editorPerms = PERM_READ | PERM_WRITE;  // 011 = 3
$adminPerms  = PERM_READ | PERM_WRITE | PERM_DELETE; // 111 = 7

echo $editorPerms; // 3
echo $adminPerms;  // 7

Checking a specific flag

AND & masks all other bits; the result is non-zero only when the specific flag bit is set in the permissions integer.

Example · php
<?php
const PERM_READ   = 1;
const PERM_WRITE  = 2;
const PERM_DELETE = 4;

$userPerms = 3; // READ | WRITE

if ($userPerms & PERM_DELETE) {
    echo 'Can delete';
} else {
    echo 'No delete permission'; // prints this
}

if ($userPerms & PERM_READ) {
    echo 'Can read'; // prints this
}

Toggle a bit with XOR

XOR ^ flips a bit: 0 XOR 1 = 1 (on), 1 XOR 1 = 0 (off) — perfect for toggle operations.

Example · php
<?php
const FEATURE_DARK_MODE = 0b0001;
const FEATURE_BETA_UI   = 0b0010;

$flags = 0b0000;
$flags ^= FEATURE_DARK_MODE;  // turn ON
echo decbin($flags);           // 1

$flags ^= FEATURE_DARK_MODE;  // turn OFF
echo decbin($flags);           // 0

Discussion

  • Be the first to comment on this lesson.