The array_filter function filters the array elements based on the user-defined function.
array_filter function passes each value of the array to the user-defined function. The user-defined function returns true or false. If the returned value is true, it will be kept in the output array, else it will be removed from the output as the filtering function returns false on it.
What is the syntax of the array_filter function in PHP?
array_filter(array, callbackfunction, flag)
Parameters | Details |
---|---|
array | Specify the array to filter – Required |
callback function | Specify the callback function to use – Optional |
flag | Optional. Specify the arguments for the callback function ARRAY_FILTER_USE_KEY: The user-defined function will receive the key only. ARRAY_FILTER_USE_BOTH – The user-defined function will receive both the key and the value. |
Example of the array_filter function
<?php
function test_odd($var)
{
return($var & 1);
}
$a1=array(1,3,2,3,4);
print_r(array_filter($a1,"test_odd"));
?>
In the above example, the user_defined function receives values from the array_filter function one by one. If the value meets the condition specified in the user-defined function, it will return true and will remain in the resultant array. Otherwise, it will be removed from the output array.