PHP array_filter() Function
The PHP array_filter() function filters elements of an array using a callback function. This function iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array.
Note: This function preserves the array key, therefore may result in gaps if the array was indexed. The result array can be reindexed using the array_values() function.
Syntax
array_filter(array, callback, mode)
Parameters
array |
Required. Specify the array to iterate over. |
callback |
Optional. Specify the callback function to use. If no callback function is supplied, all empty entries of array will be removed. |
mode |
Optional. Specify flag which determines what arguments are sent to callback:
|
Return Value
Returns the filtered array.
Exceptions
NA.
Example:
The example below shows the usage of array_filter() function.
<?php function odd($x) { //returns true when x is odd, //else returns false return $x & 1; } function even($x) { //returns true when x is even, //else returns false return !($x & 1); } $Arr1 = array(10, 11, 12, 13, 14, 15, 16); $Arr2 = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6); echo "Even values from Arr1\n"; //filtering only even values from Arr1 print_r(array_filter($Arr1, "even")); echo "\nOdd values from Arr2\n"; //filtering only odd values from Arr2 print_r(array_filter($Arr2, "odd")); ?>
The output of the above code will be:
Even values from Arr1 Array ( [0] => 10 [2] => 12 [4] => 14 [6] => 16 ) Odd values from Arr2 Array ( [a] => 1 [c] => 3 [e] => 5 )
Example: array_filter() without callback function
If no callback function is supplied, all empty entries of the array is removed as shown in the example below:
<?php $Arr = array(0 => 'red', 1 => false, 2 => -1, 3 => '0', 4 => null, 5 => '', 6 => 0); //after removing empty entries print_r(array_filter($Arr)); ?>
The output of the above code will be:
Array ( [0] => red [2] => -1 )
Example: array_filter() with mode parameter
The mode parameter can be used to determine what arguments are sent to callback function. Consider the example below:
<?php function mode_key($k) { return ($k%2 == 0); } function mode_value_key($v, $k) { return ($v%2 == 0) && ($k%2 == 0); } $Arr = array(10, 12, 15, 17, 20, 22, 25); //selecting only even keys print_r(array_filter($Arr, 'mode_key', ARRAY_FILTER_USE_KEY)); echo"\n"; //selecting even keys and values print_r(array_filter($Arr, 'mode_value_key', ARRAY_FILTER_USE_BOTH)); ?>
The output of the above code will be:
Array ( [0] => 10 [2] => 15 [4] => 20 [6] => 25 ) Array ( [0] => 10 [4] => 20 )
❮ PHP Array Reference