This built-in function in PHP is used to filter the elements of an array using a user-defined function which is also called a callback function. The array_filter() function iterates over each value in the array, passing them to the user-defined function or the callback function. If the callback function returns true then the current value of the array is returned into the result array otherwise not. This way the keys of the array gets preserved, i.e. the key of element in the original array and output array are same.
array array_filter($array, $callback_function, $flag)
Parameters: The function takes three parameters, out of which one is mandatory and the other two are optional.
- $array (mandatory): This refers to the input array on which the filter operation is to be performed.
- $callback_function (optional): Refers to the user-defined function. If the function is not supplied then all entries of the array equal to FALSE , will be removed.
- $flag (optional): Refers to the arguments passed to the callback function.
- ARRAY_FILTER_USE_KEY – passes key as the only argument to a callback function, instead of the value of the array.
- ARRAY_FILTER_USE_BOTH – passes both value and key as arguments to callback instead of the value.
Return Value: The function returns a filtered array.
Below is a program showing how to return or filter out even elements from an array using array_filter() function.
Array (  => 12  => 0  => 0  => 18  => 0  => 46 )
In this example, we will not pass the callback function and let’s see the output. We will see that the 0 or false elements are not printed:
Array (  => 12  => 18  => 27  => 46 )
- How to get the function name inside a function in PHP ?
- PHP | pos() Function
- D3.js | d3.lab() Function
- D3.js | d3.map.set() Function
- D3.js | d3.hcl() Function
- PHP | key() Function
- PHP | sin( ) Function
- PHP | cos( ) Function
- p5.js | second() function
- p5.js | max() function
- p5.js | nfp() Function
- p5.js | value() Function
- p5.js | abs() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.