Hello-World - 6 months ago 37

PHP Question

in PHP in the line below

`return($var & 1);`

`<?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.