How to Filter Odd and Even numbers from an Array in PHP with array_filter

Suppose you have array with value of 1 to 12.
And you want to separate odd and even numbers in different array, then use below code.
<?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 :\n";
echo "<pre>";
print_r(array_filter($array1, "odd"));
echo "</pre>";
echo "Even:\n";
echo "<pre>";
print_r(array_filter($array2, "even"));
echo "</pre>";
?>


Output:

Odd :

Array
(
[a] => 1
[c] => 3
[e] => 5
)

Even:

Array
(
[0] => 0
[1] => 6
[3] => 8
[5] => 10
[7] => 12
)



If you want to use array_filter with a class method as the callback, you can use a psuedo type callback like below, which will print only even numbers from 1 to 10 array.
<?php class Test {
   public function doFilter($array)
   {
       return array_filter($array, array($this, 'callbackMethodName'));
   }

   protected function callbackMethodName($element)
   {
       return $element % 2 === 0;
   }
}

$example = new Test;
echo "<pre>";
print_r($example->doFilter(range(1, 10)));
echo "</pre>";?>




Output:

Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)

And one another example of array_filter within a class to access a protected method from that same class:
<?php

class Bar {
      public function foo()
      {
          $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

          print_r(array_filter($array1, array($this, 'baz')));
      }

      protected function baz($var)
      {
          return($var & 1);
      }
}

$bar = new Bar();

echo "<pre>";
print_r($bar->foo());
echo "</pre>";
?>



Output:

Array
(
 [a] => 1
 [c] => 3
 [e] => 5
)

Post a Comment

0 Comments