2

Possible Duplicate:
Understanding PHP's & operator

I was just looking at array_filter() function doc and they had the following code to return odd numbers...

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

Why does $var & 1 return odd number? how does that work?

Community
  • 1
  • 1
CodeCrack
  • 5,003
  • 11
  • 40
  • 71
  • 2
    See http://stackoverflow.com/questions/600202/understanding-phps-operator – AHungerArtist Dec 21 '11 at 18:57
  • Also [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Herbert Dec 21 '11 at 19:33

3 Answers3

6

& is bitwise and. It acts as a mask on the bits of $var. All odd numbers end with 1

no  bit  &1
1   001  1
2   010  0
3   011  1
4   100  0
5   101  1
6   110  0
7   111  1
knittl
  • 216,605
  • 51
  • 293
  • 340
3

You are using a bitwise function with always returns 1 when anded with an odd number.

A few examples:

 11 = 3
 01 = 1
----
 01 = odd -- return 1 (true)

 100 = 4
  01 = 1
-----
 000 = even -- return 0 (false)

One more:

 10101 = 21
    01 = 1
-------
 00001 = odd -- return 1 (true)
Naftali
  • 142,114
  • 39
  • 237
  • 299
0

That function return 1 if var is an odd number, 0 otherwise. "&" is the AND binary operator, so it considers the last binary digit of a number.

For example:

5 in binary is 101 -> 101 & 1 = 1 -> odd number.

8 in binary is 1000 -> 1000 & 1 = 0 -> even number.

ocirocir
  • 2,933
  • 1
  • 21
  • 32