PHP 8 reference · Array Functions
PHP array_filter() Function
Keep only the elements for which a callback returns true. Without a callback it removes empty values; keys are kept.
PHP 8 Since 4.0
Syntax
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Parameters
| Parameter | Description |
|---|---|
array |
The input array. |
callback optional |
Returns true to keep an element. Without one, falsy values (0, "", null, false, []) are removed. |
mode optional |
ARRAY_FILTER_USE_KEY passes the key, ARRAY_FILTER_USE_BOTH passes value and key. Default: 0 |
Return value
The filtered array, with the original keys.
Examples
<?php
$numbers = [1, 2, 3, 4, 5, 6];
print_r(array_filter($numbers, fn($n) => $n % 2 === 0));
Output
Array
(
[1] => 2
[3] => 4
[5] => 6
)<?php
print_r(array_values(array_filter(["a", "", null, "b", 0, "0"])));
Output
Array
(
[0] => a
[1] => b
)<?php
$env = ["APP_NAME" => "camel", "DB_HOST" => "localhost", "APP_DEBUG" => "1"];
print_r(array_filter($env, fn($k) => str_starts_with($k, "APP_"), ARRAY_FILTER_USE_KEY));
Output
Array
(
[APP_NAME] => camel
[APP_DEBUG] => 1
)Common mistakes
- Keys are preserved, so the result can have gaps (
[1 => …, 3 => …]) and turns into a JSON object. Wrap it inarray_values()for a plain list. - Without a callback the string
"0"is removed too, because it's falsy.
Version history
In other languages
filter()· Pythonarray.filter()· JavaScript
Related
array_map()· Apply a callback to every element of one or more arrays and return a new array of the results.array_reduce()· Reduce an array to a single value by passing a running total and each element to a callback.array_values()· Return all the values of an array as a list re-indexed from 0. Often used after array_filter() or unset().array_find()· Return the first element for which a callback returns true, or null if none match. Added in PHP 8.4.- PHP Array Functions · tutorial
- PHP Arrays · tutorial