Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

php - callback function return return($var & 1)?

I have read the PHP Manuel about array_filter

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :
";
print_r(array_filter($array1, "odd"));
echo "Even:
";
print_r(array_filter($array2, "even"));
?>

Even I see the result here :

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

But I did not understand about this line: return($var & 1); Could anyone explain me about this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...