-2

for array_filter, I considered an example from php official site. I found a example there

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

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

both function return return($var & 1) and return(!($var & 1)); I can not understand properly what does it mean and specially why 1 is there in return

  • 2
    possible duplicate of [Understanding PHP & (ampersand, bitwise and) operator](http://stackoverflow.com/questions/600202/understanding-php-ampersand-bitwise-and-operator) – fedorqui Jan 15 '15 at 10:49
  • Actually the returns are different. I suggest what @fedorqui commented just right before me. – Masiorama Jan 15 '15 at 10:50
  • I would suggest reading this topic: http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – Forien Jan 15 '15 at 10:51

1 Answers1

0

It's pretty simple: & is a bitwise AND operator and it works as followed:

    A  |  B
---------------
    0  |  0   -> 0
    1  |  0   -> 0
    0  |  1   -> 0
    1  |  1   -> 1

And if you take as an example 2, 3 and 6 for odd then this is what's going on:

0000 0010  -> 2
0000 0001  -> 1
--------- &
0000 0000 = return 0

0000 0011  -> 3
0000 0001  -> 1
--------- &
0000 0001 = return 1

0000 0110  -> 6
0000 0001  -> 1
--------- &
0000 0000 = return 0

So in other words if the first digit (1) is 'on' it's going to return 1 because it's odd and if not it's going to return 0

And the same is going on for even just with a NOT (!) operator

Rizier123
  • 58,877
  • 16
  • 101
  • 156