PHP Bitwise Operators: AND, OR, XOR, NOT with Examples

php bitwise operators

Bitwise operators use symbols like &, |, and ^, and they work at the binary level. But once you understand what they do, you can use them to manage flags and handle permissions with fewer lines.

Understand the Bitwise Operators

Bitwise operators work directly with the binary form of integers. Each integer is a set of bits (0s and 1s). Bitwise operators perform actions on each bit, not on the whole number.

If you compare this to regular math operators, the difference becomes clear. Math operators work on entire values. Bitwise operators go inside the number and change its inner parts.

You use bitwise operators when you need to:

  • Handle permission flags
  • Store many true/false states in a single number
  • Speed up certain checks or changes
  • Toggle bits in low-level tasks like encoding or system flags

They save memory and reduce checks. But they only make sense when you understand how binary works.

Here are the basic rules of the binary system:

Each number in binary is a set of bits. A bit is either 0 or 1. Each position in a binary number stands for a power of 2.

For example:

Decimal:  5
Binary: 0101

The rightmost bit is the 1s place. Then comes 2s, 4s, and so on. This pattern is the foundation of all bitwise work.

Let’s move on to the following section to see types of bitwise operators in PHP.

Types of Bitwise Operators in PHP

Here are the bitwise operators you can use:

  • & – AND
  • | – OR
  • ^ – XOR
  • ~ – NOT
  • << – Left shift
  • >> – Right shift

Each one follows a simple rule. They act on each bit and return a new result. Let’s take a look at each one in-depth.

Bitwise AND (&)

The bitwise AND operator (&) compares two numbers in their binary (0s and 1s) form. It looks at each bit (number part) from both numbers. If both bits are 1, it keeps the 1. If not, it puts a 0.

For example: ( 5 and 3 )

5 = 0101  
3 = 0011  

Now we compare them bit by bit:

  0101   (5)  
& 0011 (3)
-------
0001 = 1

So, 5 & 3 gives us 1.

Here is PHP example:

$a = 5;
$b = 3;

$result = $a & $b;

echo $result;  // Output: 1

Bitwise OR (|)

The Bitwise OR operator helps you to compare two numbers bit by bit. If at least one of the bits is 1, the result is 1. If both bits are 0, the result is 0.

Here is an example:

$a = 5;
$b = 3;

$result = $a | $b;

echo $result; // Output: 7

It converts numbers to binary (4 bits):

DecimalBinary
50101
30011

Now do Bitwise OR:

     0101   (5)
OR 0011 (3)
--------------
0111 = 7

So, Bit by Bit comparison:

Bit PositionBit in $a (5)Bit in $b (3)Result (OR)
8’s place000
4’s place101
2’s place011
1’s place111

The final binary is 0111 → which is 7 in decimal.

Bitwise XOR (^)

The XOR means “exclusive OR“. It helps you to compare two binary numbers together bit by bit:

  • If the bits are the same, the result is 0.
  • If the bits are different, the result is 1.

The example is (5 ^ 3).

Here are the numbers in binary:

DecimalBinary
50101
30011

Apply XOR:

     0101   (5)
XOR 0011 (3)
--------------
0110 = 6

Here is PHP example:

$a = 5;
$b = 3;

$result = $a ^ $b;

echo $result; // Output: 6 

Bit by Bit Comparison:

Bit PositionBit in $aBit in $bResult (XOR)
8’s place000
4’s place101
2’s place011
1’s place110

Result: 0110 → which is 6 in decimal.

Bitwise NOT (~)

Bitwise NOT flips all the bits of a number:

  • 1 becomes 0
  • 0 becomes 1

It’s called “NOT” because it inverts the bits.

Here is an example: ~5

Binary of 5:

5 = 00000101  (It shows 8 bits)

When you flip all bits with ~:

~00000101 = 11111010

This binary number is -6 in decimal in PHP.

Here is a PHP example:

$a = 5;

$result = ~$a;

echo $result; // Output: -6

PHP uses two’s complement to store negative numbers:

  • Flip all bits
  • Add 1

So:

Original: 00000101 (5)
NOT: 11111010
→ This is -6 in two’s complement form

Here is a table that shows you what happened.

OperatorNameActionExample
~Bitwise NOTFlips all bits (1 ↔ 0)~5 = -6

Bitwise Shift Operators

There are two main shift operators:

OperatorNameWhat It Does
<<Left ShiftMoves bits to the left, adds 0s on right
>>Right ShiftMoves bits to the right, removes bits on right

Left Shift (<<) :

It moves bits to the left and fills the empty spots on the right with 0s.

For example: 5 << 1

Convert 5 to binary:

5 = 0101

Shift left by 1:

0101 << 1 = 1010

This is 10 in decimal.

Here is the PHP example:

$a = 5;
$result = $a << 1;

echo $result; // Output: 10 

Each shift left is like multiplying by 2: 5 << 1 = 5 * 2 = 10.

Right Shift (>>):

It moves bits to the right and removes bits from the right side. Here is an example: 5 >> 1.

5 in binary:

5 = 0101

Shift right by 1:

0101 >> 1 = 0010

This is 2 in decimal.

Here is the PHP example:

$a = 5;
$result = $a >> 1;

echo $result; // Output: 2

Each shift right is like dividing by 2 (ignoring remainder): 5 >> 1 = 5 / 2 = 2

Bitwise Operations vs Logical Operations

Bitwise operations work on bits of integers, useful for flags and binary data.
Logical operations handle boolean values, used in conditions like if or while.
They look similar (& vs &&) but behave very differently.

  • Use when you’re working with individual bits in a number.
  • Often used for flags, permissions, binary data.
TypeWorks OnOperates At the Level Of
BitwiseNumbers (integers)Bits (0s and 1s) inside numbers
LogicalBoolean values (true/false)Whole values, not bits

Here is a table shows you a comparison:

FeatureBitwiseLogical
Works onBits (0s and 1s)Booleans (true/false)
Data TypeIntegersBoolean
Common usePermissions, flagsConditions, logic
Example5 & 31true && falsefalse
Operates onEach bitWhole value

Combine Bitwise Operators with Conditional Logic in PHP

You often do this when you want to store multiple options or permissions in a single number (with bits), and then check those options with an if statement.

This is very common in things like:

  • User roles or access rights
  • Settings or toggles
  • Status flags

Let’s say we define 3 permissions:

define("READ",   1);  // 0001
define("WRITE",  2);  // 0010
define("DELETE", 4);  // 0100

A user can have more than one permission by using Bitwise OR (|):

$user_permissions = READ | WRITE;  // 0001 | 0010 = 0011 (value: 3)

Now, you can use conditional logic to check if a user has a specific permission using Bitwise AND (&):

if ($user_permissions & READ) {
    echo "User can read.\n";
}

if ($user_permissions & WRITE) {
    echo "User can write.\n";
}

if ($user_permissions & DELETE) {
    echo "User can delete.\n";
} else {
    echo "User CANNOT delete.\n";
}

Output:

User can read.
User can write.
User CANNOT delete.
  • $user_permissions & READ checks if the READ bit is set
  • If it’s not zero, it means the permission is present
  • The if condition runs based on the result

Wrapping Up

In this article, you learned how bitwise operators work at the binary level in PHP and how to apply them in real-world cases like permissions and flags. You also saw how they differ from logical operators and how to use them inside conditionals.

Here is a quick recap:

  • Bitwise operators work on the binary (bit) level of integers.
  • Logical operators work on boolean values like true and false.
  • & (AND) returns 1 only if both bits are 1.
  • | (OR) returns 1 if at least one bit is 1.
  • ^ (XOR) returns 1 if bits are different.
  • ~ (NOT) flips all bits (1 becomes 0, and 0 becomes 1).
  • << (Left Shift) moves bits left and multiplies the number by 2.
  • >> (Right Shift) moves bits right and divides the number by 2.
  • Bitwise operators are great for handling multiple options in one number.
  • You can combine bitwise checks with if statements to test for specific flags.
  • Bitwise operations can help make your code faster and more efficient, especially for low-level tasks.

FAQ’s

What are bitwise operators in PHP and how do they work?

Bitwise operators in PHP work at the binary level of integers. They perform operations on individual bits (0s and 1s) rather than whole numbers. Examples include & (AND), | (OR), ^ (XOR), ~ (NOT), <> (Right Shift).

When should I use bitwise operators in PHP?

Use them to handle permission flags, store multiple boolean states in a single number, toggle bits, or speed up low-level logic. They're common in access control, system flags, and binary encoding tasks.

What is the difference between bitwise and logical operators in PHP?

Bitwise operators work on the bits of integers, while logical operators work on boolean values. For example, & compares bits, while && evaluates true/false expressions.

What does the bitwise NOT (~) operator do in PHP?

The ~ operator flips all bits of a number. For example, ~5 becomes -6 because PHP uses two’s complement to represent negative numbers.

Similar Reads

PHP For Loop: Run Code Using a Counter with Examples

You may need to repeat tasks in PHP. The PHP for loop solves this by letting you run code many…

PHP array_diff_uassoc: How to Compare Arrays with Keys

PHP array_diff_uassoc compares arrays by values and keys. You can also pass a custom function to compare keys in your…

PHP Object | How to Create an Instance of a Class

The PHP object is an instance from the PHP class or the main data structure that is already been created…

PHP filter_list(): List Available Filters

PHP introduces the filter_list() function to give developers a way to check all available filters in the filter extension. This…

PHP $_REQUEST: Learn How to Capture User Inputs

Today, we will discuss the most prominent and useful superglobal in PHP, $_REQUEST, to get user input. The $_REQUEST array lets you retrieve…

PHP array_all Function: How it Works with Examples

PHP 8.4 released a new built-in function, array_all checks to check if all array values meet a condition. It gives…

PHP substr Function: How to Extract and Manipulate Strings

The substr() function in PHP returns part of a string. You give it a string, a starting point, and optionally…

PHP Type Hints: Ensuring Data Integrity

PHP-type hinting is something that keeps your code in check and helps your functions receive just the right types of…

Understanding the PHP Enumerable

Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…

PHP is_dir Function: Check if a Directory Exists

Sometimes, when you run a script, you may encounter an error because the directory you're trying to access doesn't exist.…

Previous Article

How to Install PHP on a Raspberry Pi

Next Article

PHP substr Function: How to Extract and Manipulate Strings

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.