What is the array_filter function in PHP?
The array filter function is used to filter the array based on a callback function.
Imagine this, given an array, you want to find out values that are greater than zero. You can use a callback function to check whether or not a given value is greater than zero. The array_filter uses this callback function to filter out the array based on our requirements. Each value of an array is passed into our function. Callback function will return a boolean true or false. Given true, The value is returned along with its corresponding index in the array.
Syntax
array_filter(array, callbackfunction, flag)
Parameters
-
array. It is a required parameter and refers to the name of the array that needs to be filtered. -
**
callbackfunction. It is an optional parameter that refers to the callback function being used to filter the array. -
flag. It is an optional parameter. It is used to specify what kind of arguments can be taken by callback. For example, if the array needs to be filtered based on the index of array, then we do need to pass the values of these indexes. In that case, a user can passARRAY_FILTER_USE_KEYas a flag parameter, which only takes all the keys of the array. By default, both keys and values are sent as arguments – this is equivalent toARRAY_FILTER_USE_BOTH.
<?php// The function test greater is a callback function tp// check the numbers of array to find which number are greater// than zero.function test_greater($value){return($value > 0);}// array_filter filters the array of numbers to return// values and the indexes of which satisfy our callback function.// In this case, index 2 and 3 along with their values// are returned.$arr=array(-5,-9,12,6,-7);print_r(array_filter($arr,"test_greater"));?>
Free Resources