English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

hi guys, i don't really get the meaning of return ($var & 1). Can u make it clear?

function odd($var)
{
return($var & 1);
}

function even($var)
{
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 :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

Thanx in advance

2007-02-19 21:03:23 · 4 answers · asked by ? 2 in Computers & Internet Programming & Design

4 answers

& is a bitwise operator which works with the bits in the variables.

($var & 1) will give you the bits which are common in both. For example if $var = 2 (represented as 8-bit = 00000010) and 1 (represented as 8-bit = 00000001), there are 0 (zero) common bits which, when converted to boolean, will return false.

if $var = 3 (8-bit = 00000011) and 1 (8-bit = 00000001) has 1 common bit and will return true.

thus "return ($var & 1)" will return true for odd (1,3,5,7 ... ) numbers as they will always have 1 bit common while "return (!($var & 1)) will return true for even (2,4,6,8 ...) numbers as they will not have any bit common.

2007-02-19 22:46:30 · answer #1 · answered by Kamran 2 · 0 0

Look at the following representation of integers in 8-bit.

1----->00000001
2----->00000010
3----->00000011
4----->00000101
......

So the & operator compares the bits of $var and 1. In case of odd numbers the left most bit (1st) is set. So if($var&1) returns true.
And in case of even, if(!$var&1) returns true.

array_shift returns those elements in an array for which it gets true from callback function (2nd parameter).

2007-02-19 22:44:09 · answer #2 · answered by Atif Majid 3 · 0 0

return($var & 1) in this & is bitwise AND operator.
and the variable $var and 1 are comparing using AND operator...

2007-02-19 21:52:37 · answer #3 · answered by Shree J 2 · 0 0

I wouldn't like to say for sure, but I would assume a single call to a local function would probably be slightly faster than a call to an objects method, as you firstly have to instantiate that object, then call it's method. However, as your project is to grow in size, it's almost certainly going to be more cost effective to have it object orientated as opposed to including/requiring a bunch of files containing generic utility functions.

2016-05-23 22:08:49 · answer #4 · answered by Anonymous · 0 0

fedest.com, questions and answers