Bitwise Operators

Bitwise operators aren't used very often, and even then only by more advanced PHP programmers. They manipulate the binary digits of numbers, which is more control than many programmers need. The bitwise operators are listed in Table 6-4.

Table 6-4. The bitwise operators

&

And

Bits set in $a and $b are set.

|

Or

Bits set in $a or $b are set.

^

Xor

Bits set in $a or $b, but not both, are set.

~

Not

Bits set in $a are not set, and vice versa.

<<

Shift left

Shifts the bits of $a to the left by $b steps. This is equivalent, but faster, to multiplication. Each step counts as "multiply by two." If you try this with a float, PHP ignores everything after the decimal point and treats it as an integer.

>>

Shift right

Shifts the bits of $a to the right by $b steps.

To give an example, the number eight is represented in eight-bit binary as 00001000. In a shift left, <<, all the bits literally get shifted one place to the left, giving 00010000, which is equal to sixteen. Eight shifted left by four gives 10000000, which is equal to 128—the same number you would have gotten by multiplying eight by two four times in a row.

The & (bitwise and) operator compares all the bits in operand one against all the bits on operand two, then returns a result with all the joint bits set. Here's an example: given 52 & 28, we have the eight-bit binary numbers 00110100 (52) and 00011100 (28). PHP creates a result of 00000000, then proceeds to compare each digit in both numbers—whenever ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.