in PHP in the line below return($var & 1);
What does this mean, what does the & mean in this context?
<?php
function test_odd($var)
{
return($var & 1);
}
$a1=array("a","b",2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
in PHP in the line below return($var & 1);
What does this mean, what does the & mean in this context?
<?php
function test_odd($var)
{
return($var & 1);
}
$a1=array("a","b",2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
The &
(ampersand) operator does bitwise AND
.
If $var
is odd it returns 1
, otherwise 0
.
Let's say $var = 13
, that in binary is 1101
(because 13 = 2^3 + 2^2 + 2^0
).
When you do 1101 & 0001
you get 0001
. So you can either get 1
if $var
has its last bit 1 (meaning it's odd) or 0
if $var
has 0 as the last bit, meaning that $var
is written as a sum of powers of two, without 2^0` meaning its even.