1

I am digging deeper into the array_filter() of php. I've understand the basic idea of it but fall into new problem.

$array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];

$result = array_filter($array, function ($var){
              return $var & 1;
          });

If I dump the $result it looks like:

array:3 [
  "a" => 1
  "c" => 3
  "e" => 5
]

I want to know how return $var & 1; works behind the scene in the callback function of array_filter() .

2
  • 1
    Not sure what the actual question is here. Sounds like you are simply not aware what the & operator does? php.net/manual/en/language.operators.bitwise.php Commented May 5, 2020 at 12:44
  • Exactly. I was not aware of bitwise operator. Thanks Commented May 5, 2020 at 12:52

1 Answer 1

4

array_filter() keeps the values that produce truthy result for the callback and removes the values that don't.

This expression actually checks if the number is odd:

$number & 1

Why? because it performs bitwise AND operation with 1. So, odd numbers have 1 as their last digit in binary representation and even numbers have 0.

When you perform bitwise AND, every corresponding digit computes to 1 when both digits are 1 and 0 otherwise. So:

1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
// etc.

Now, you can apply AND operation:

    0001 = 1
AND 0001
  = 0001 = 1 (odd)

    0010 = 2
AND 0001
  = 0000 = 0 (even)

    1001 = 9
AND 0001
  = 0001 = 1 (odd)

I hope you get the idea.

Sign up to request clarification or add additional context in comments.

5 Comments

Hm... That answers the title but not the acutal question.
I thought that % 1 was OP's trial to determine the odd.
You answer "Piece of cake. You need a modulo operator:". The question was " I want to know how return $var & 1; works behind the scene in the callback function of array_filter() ." :)
No problem. I just was nitpicking
Awesome. Couldn't be better.

Your Answer

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.