Understanding PHP & (ampersand, bitwise and) operator

ryonlife picture ryonlife · Mar 1, 2009 · Viewed 26.1k times · Source

I often use ($var & 1) in my code, which returns true if $var is an odd number and false if it's an even number.

But what does "&" actually do?

Answer

Marius picture Marius · Mar 1, 2009

& is binary and. If you have a binary value, and you and with another binary value, then the result will be the bitwise and of the two. An example:

  01101010
& 01011001
= 01001000

The rightmost bit is either a 1 (and in that case the number is an odd number) or it is a 0, in which case the number is even. If you & a number with 1, you only look at the least significant bit, and the if checks if the number is a 1 or a 0. As others have mentioned, look at the bitwise operators for info on how they work.