Home >>PHP Array Functions >PHP array_filter() Function

PHP array_filter() Function

PHP array_filter() Function

PHP array_filter() Function is used to filter the elements of any given array using a user-defined function which is also called a callback function. It iterates over each value in the array, passing them to the user-defined function or the callback function. It takes three parameters out of which one is mandatory and the other two are optional.

Syntax:

 array_filter($array, $callbackfunction, $flag);

Parameter Values

Parameter Description
array This is a required parameter. This parameter defines the array to filter.
callbackfunction This is an optional parameter. This parameter defines the callback function to use.
flag This is an optional parameter. This parameter defines what arguments are sent to callbackfunction.

Here is an example of array_filter() function in PHP:

<html>
<body>
<pre>
<?php
function odd($var)
  {
  return($var%2);
  }
$x=array(1,2,3,4,5,6,7,8,9,10);
print_r(array_filter($x,"odd"));
?>
</pre>
</body>
</html>
Output:
Array
(
    [0] => 1
    [2] => 3
    [4] => 5
    [6] => 7
    [8] => 9
)

Example 2:

<html>
<body>
<pre>
<?php
function even($var)
  {
  if($var%2==0)
  return TRUE;
  else
  return FALSE;
  }
	for($i=1;$i<=20;$i++)
	{
	$x[]= $i;
	}
print_r(array_filter($x,"even"));
?>
</pre>
</body>
</html>
Output:
Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
    [11] => 12
    [13] => 14
    [15] => 16
    [17] => 18
    [19] => 20
)

No Sidebar ads