I have read the PHP Manuel about array_filter
It is performing a bitwise AND with $var and 1. Since 1 only has the last bit set, $var & 1
will only be true if the last bit is set in $var. And since even numbers never have the last bit set, if the AND is true the number must be odd.
$var & 1
- is bitwise AND
it checks if $var
is ODD value
0 & 0 = 0,
0 & 1 = 0,
1 & 0 = 0,
1 & 1 = 1
so, first callback function returns TRUE only if $var is ODD, and second - vise versa (! - is logical NOT).
You know &&
is AND
, but what you probably don't know is &
is a bit-wise AND
.
The &
operator works at a bit level, it is bit-wise. You need to think in terms of the binary representations of the operands.
e.g.
710 & 210 = 1112 & 0102 = 0102 = 210
For instance, the expression $var & 1
is used to test if the least significant bit is 1
or 0
, odd or even respectively.
$var & 1
010 & 110 = 0002 & 0012 = 0002 = 010 = false (even)
110 & 110 = 0012 & 0012 = 0012 = 110 = true (odd)
210 & 110 = 0102 & 0012 = 0002 = 010 = false (even)
310 & 110 = 0112 & 0012 = 0012 = 110 = true (odd)
410 & 210 = 1002 & 0012 = 0002 = 010 = false (even)
and so on...
An odd number has its zeroth (least significant) bit set to 1
:
v
0 = 00000000b
1 = 00000001b
2 = 00000010b
3 = 00000011b
^
The expression $var & 1
performs a bitwise AND operation between $var and 1 (1 = 00000001b
). So
the expression will return:
$var
has its zeroth bit set to 1 (odd number)$var
has its zeroth bit set to 0 (even number)& is a bitwise AND on $var.
If $var is a decimal 4, it's a binary 100. 100 & 1 is 100, because the right most digit is a 0 in $var - and 0 & 1 is 0, thus, 4 is even.
&
it's the bitwise operator. It does the AND with the corrispondent bit of $var
and 1
Basically it test the last bit of $var to see if the number is even or odd
Example with $var binary being 000110 and 1
000110 &
1
------
0
0 (false) in this case is returned so the number is even, and your function returns false accordingly