25

Possible Duplicate:
Reference - What does this symbol mean in PHP?

When I was reading this php page, I was not sure what & is doing in $var & 1.

function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

Is it returning a reference? I am not sure.

If you can explain it or direct me a php page, I will appreciate it.

Thanks in advance.

Community
  • 1
  • 1
shin
  • 31,901
  • 69
  • 184
  • 271

3 Answers3

29

It's a bitwise-AND operation. All odd numbers have LSB (least significant bit set to 1), even numbers - 0.

So it simply "ANDs" two numbers together. For example, 5. It is represented as 101 in binary. 101 & 001 = 001 => true, so it is odd.

Dmitri
  • 2,451
  • 6
  • 35
  • 55
9

It is performing bitwise ANDing. That is a bitwise operator

$a & $b Bits that are set in both $a and $b are set.


In this case, return($var & 1); will do a bitwise AND against 0000....0001 returning 1 or 0 depending on the last bit of $var.

If the binary representation of a number ends in 0, it is even (in decimal).

If the binary representation of a number ends in 1, it is odd (in decimal).

Community
  • 1
  • 1
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
4

& is the bitwise and operator. In this case it will return 1 if $var is odd, 0 if $var is even.

Joakim Nohlgård
  • 1,832
  • 16
  • 16