-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

asked Jan 15, 2015 at 10:47
3

1 Answer 1

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

answered Jan 15, 2015 at 10:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.