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() .
Advertisement
Answer
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.