PHP Bitwise Operators

PHP provides a set of bitwise operators that allow you to work directly with the binary representation of numbers. These operators perform bit-level operations, which can be useful for tasks such as flag handling and low-level programming.

1. Common Bitwise Operators

  • & : Bitwise AND
  • | : Bitwise OR
  • ^ : Bitwise XOR
  • ~ : Bitwise NOT (Complement)
  • << : Left Shift
  • >> : Right Shift

2. How Bitwise Operators Work

Bitwise operators work on the binary representation of integers. For example, consider the numbers 5 and 3:

  • 5 in binary is 0101
  • 3 in binary is 0011

πŸ“ Example 1: Bitwise AND (&)

Performs AND operation between two numbers.

<?php
$a = 6;  // 110 in binary
$b = 3;  // 011 in binary
echo $a & $b; // Output: 2 (010 in binary)
?>
    

Try It Now

πŸ“ Example 2: Bitwise OR (|)

Returns 1 if at least one bit is 1.

<?php
$a = 6;  // 110 in binary
$b = 3;  // 011 in binary
echo $a | $b; // Output: 7 (111 in binary)
?>
    

Try It Now

πŸ“ Example 3: Bitwise XOR (^)

Returns 1 if only one of the bits is 1.

<?php
$a = 6;  // 110 in binary
$b = 3;  // 011 in binary
echo $a ^ $b; // Output: 5 (101 in binary)
?>
    

Try It Now

πŸ“ Example 4: Bitwise NOT (~)

Flips all bits of a number (may give negative results due to 2’s complement representation).

<?php
$a = 6; // 110 in binary
echo ~ $a; // Output: -7 (due to 2's complement)
?>
    

Try It Now

πŸ“ Example 5: Left Shift (<<)

Moves bits to the left (multiplies by powers of 2).

<?php
$a = 3; // 011 in binary
echo $a << 2; // Output: 12 (1100 in binary)
?>
    

Try It Now

πŸ“ Example 6: Right Shift (>>)

Moves bits to the right (divides by powers of 2).

<?php
$a = 8; // 1000 in binary
echo $a >> 2; // Output: 2 (10 in binary)
?>
    

Try It Now

🎯 Recap – Quick Takeaways

  • & (AND) β†’ Both bits must be 1
  • | (OR) β†’ At least one bit must be 1
  • ^ (XOR) β†’ Only one bit can be 1
  • ~ (NOT) β†’ Flips all bits
  • << (Left Shift) β†’ Moves bits left, fills with 0s
  • >> (Right Shift) β†’ Moves bits right, discards bits

πŸ“ Practice Time!

Change values in the examples and see what happens. The best way to learn is to experiment!