array_filter
Keeps the array elements that pass a test.
Available since: PHP 4
Syntax
array_filter(array $array, ?callable $callback = null, int $mode = 0): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The source array. |
| $callback | ?callable | A test function: an element stays if it returns `true`. Without it, empty values are removed. |
| $mode | int | With `ARRAY_FILTER_USE_KEY` the function receives the key, with `ARRAY_FILTER_USE_BOTH` the value and the key. |
Return value
arrayA new array with the selected elements. Keys are preserved.
Examples
Even numbers only — note the keys:
<?php
print_r(array_filter([1, 2, 3, 4], fn ($n) => $n % 2 === 0));Output:
Array
(
[1] => 2
[3] => 4
)Without a function, empty values are removed:
<?php
print_r(array_filter([0, 1, '', 'a', null]));Output:
Array
(
[1] => 1
[3] => a
)To get sequential keys, pass the result through array_values():
<?php
print_r(array_values(array_filter([1, 2, 3, 4], fn ($n) => $n % 2 === 0)));Output:
Array
(
[0] => 2
[1] => 4
)Notes
The original keys are preserved, so the result may have gaps in its numbering. Add array_values() when you need a plain list.
See also
- array_map — Applies a function to every element of an array.
- array_unique — Removes duplicate values from an array.
Related recipes
- How to check that every array element satisfies a condition
- How to check whether a number is prime
- How to count occurrences of a value in an array
- How to filter an array
- How to find an array element by a condition
- How to find duplicate values in an array
- How to remove an element from an array
- How to remove empty values from an array
In the tutorial
- Functions — How to declare and call functions in PHP — parameters, return values, types and scope.