array_filter()
array_filter() — Filters elements of an array using a callback function.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
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.
Signature
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $array | array | The array to iterate over |
| $callback | ?callable | The callback function to use |
| $mode | int | Flag determining what arguments are sent to callback: 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 Default is 0 which will pass value as the only argument to callback instead. |
Return value
Returns the filtered array.
Example
A runnable snippet:
function odd($var) { // returns whether the input integer is odd return $var & 1; } function even($var) { // returns whether the input integer is even return !($var & 1); } $array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; $array2 = [6, 7, 8, 9, 10, 11, 12]; echo "Odd :\n"; print_r(array_filter($array1, "odd")); echo "Even:\n"; print_r(array_filter($array2, "even"));
Output:
Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 )
Changelog
| Version | Change |
|---|---|
| 8.0.0 | callback is nullable now. |
| 8.0.0 | If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. |
See also
array_intersect(), array_find(), array_any(), array_map(), array_reduce()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page array_filter() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.