Hey everyone. I was reading the documentation for this function and I can't understand what the example is doing, and how it's working. Can someone explain to me what these functions are doing?

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

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

Thanks in advance,

Anthony

Recommended Answers

All 4 Replies

The functions odd and even are predicates, ie, callbacks. odd returns true if the number passed in is odd, and even returns true if the number passed in is even. (Note: the & is a bitwise AND operation which achieves this effect).

The function array filter, as the name suggests, filters specific elements from an array and returns them. How it filters is like this:

1. It goes through each element in the array.
2. It calls the predicate and passes that element as the argument.
3. If the predicate returns true: the element is added to the array of filtered elements which is returned after each element is checked.

Hi scru,

Thanks for replying! I understand how the overall function operates but I'm unsure about how the two callback functions work.

(Note: the & is a bitwise AND operation which achieves this effect).

Can you explain a bit more indepth to what this bitwise is, and how it's working in the functions?

Thanks very much,

Anthony

Bitwise operations are binary. I couldn't really explain how this particular one works that easily because it's a bit hard to grasp. Just know that:

$var & 1 is equivalent to $var % 2

ie, the remainder you get after a division by two. Since the remainder can only be less than two, it's either zero or one.

So think of it as $var & 1 checking for a remainder on division by two. If a remainder (one) is given, then the number is odd, otherwise (zero) the number is even.

Thanks very much for clearing that up!


Anthony

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.