How to use array filter in PHP

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

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.

Syntax

array_filter(array,function)

Parameter

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

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

Example

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

<html>

<body>

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

 <?php

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

 ?>

</body>

</html>

 

Output

filter.jpg

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
 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.