Bitwise Operators in PHP : Tutorial



We can perform operations of bits (binary 0s and 1s) using Bitwise operators.

Bitwise Opearators
&  :  (Bitwise AND)
|  :  (Bitwise OR)
^  :  (Bitwise EXCLUSIVE OR)
~  :  (Bitwise NOT) 
<< :  (Bitwise Shift left)
>> :  (Bitwise Shift right)

Example : AND Opearation
<?php



$a = 3;  //binary 11
$b = 2;  //binary 10


echo $a & $b; // 11 AND 10 = 10 (decimal 2)

}

?>
Output

3


Example : OR Opearation
<?php



$a = 3;  //binary 11
$b = 2;  //binary 10


echo $a | $b; // 11 OR 10 = 11 (decimal 3)

}

?>
Output

2




Example : Exclusive OR
<?php



$a = 3;  //binary 11
$b = 2;  //binary 10


echo $a | $b; // 11 Exclusive OR 10 = 1 (decimal 1)

}

?>
Output

2