Computer >> Computer tutorials >  >> Programming >> PHP

array_filter() function in PHP


The array_filter() function filters elements of an array using a user-made callback function. It returns the filtered array.

Syntax

array_filter(arr, callback, flag)

Parameters

  • arr − The array that will be filtered

  • callback − The callback function to be used

  • flag − The parameters sent to the callback function:

    • ARRAY_FILTER_USE_KEY − pass key as the only argument to callback instead of the value

    • ARRAY_FILTER_USE_BOTH − pass both value and key as arguments to callback instead of the value

Return

The array_filter() function returns the filtered array.

Example

<?php
function check($arr) {
   return(!($arr & 1));
}
$arr1 = array(3, 6, 9, 15, 20, 30, 45, 48, 59, 66);
print_r(array_filter($arr1, "check"));
?>

Output

Array
(
[1] => 6
[4] => 20
[5] => 30
[7] => 48
[9] => 66
)