How to use array filter in PHP

In this article, I will explain how the array_filter() function can be used in PHP.
  • 2422

array_filter() function in PHP

  • The array_filter() function passes each value in the array to a user define function and function returns either true or false, and returns an array only with the values that returned true.

  • In array_filter() function, Array keys are preserved.




  • array start is the required parameter. the array to iterate over.

  • function number is the required parameter. user define function.


The following example show to how the array_filter() function can be used in PHP.



<h3 style="color: darkgoldenrod;">array_filter() function example in PHP</h3>


 function odd($value)


    return($value & 1);


 function even($value)


    return(!($value & 1));


 $a1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

 $a2 = array(6, 7, 8, 9, 10, 11, 12);

 echo "Odd :<br/>";

 print_r(array_filter($a1, "odd"));

 echo "<br/>Even:<br/>";

 print_r(array_filter($a2, "even"));







You may also want to read these related articles here
Ask Your Question 
Got a programming related question? You may want to post your question here


More Articles

© 2020 DotNetHeaven. All rights reserved.