PHP Bitwise Operators

What are the Bitwise Operators?

Explanation

Bitwise operators are used to turn specific bits within an integer on or off.

Example :


<?php
echo 12
9 ; // Outputs '5'
echo 2
"3"; // Outputs 1
echo 2
"3"; // Outputs 1
?>

In the above example the binary for 12 is 1100, for 9 is 1001, when XOR operator is used it will give a value of 101 which is 5 in decimal numbers.

If both the left and right parameters are strings, it will display ASCII characters

Following are the bitwise operators available
Example Name Result
$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or Bits that are set in either $a or $b are set.
$a $b Xor Bits that are set in $a or $b but not both are set.
~ $a Not Bits that are set in $a are not set, and vice versa.
$a<<$b Shift left Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a>>$b Shift right Shift the bits of $a $b steps to the right (each step means "divide by two")

PHP Topics


Ask Questions

Ask Question