Hello-World Hello-World - 2 months ago 15
PHP Question

what does this mean return($var & 1);

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"));
?>

Answer

This does bitwise and.

So, if $var is odd it returns 1.

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 bite, meaning that $var is written as a sum of powers of two, without 2^0` meaning its even.

Comments