What does array_filter() do?
array_filter() passes each element to $callback and keeps it if the callback returns a truthy value. Without a callback it removes every falsy element (false, 0, "0", "", null, []). Keys are always preserved.
Syntax
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Parameters
$array- The array to filter.$callback- Function returning true to keep an element. If omitted, falsy values are removed.$mode-0(default) passes the value,ARRAY_FILTER_USE_KEYpasses the key,ARRAY_FILTER_USE_BOTHpasses value and key.
Return value
A new array containing only the kept elements, with their original keys. Wrap it in array_values() to get sequential keys.
array_filter() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. Keep even numbers (and reindex)
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even);
print_r(array_values($even));
Output:
Array
(
[1] => 2
[3] => 4
[5] => 6
)
Array
(
[0] => 2
[1] => 4
[2] => 6
)
2. Remove empty values (no callback)
<?php
$values = [0, 1, "", "hello", null, false, "0", [], "a"];
print_r(array_filter($values));
Output:
Array
(
[1] => 1
[3] => hello
[8] => a
)
3. Multiple conditions and multiple allowed values
<?php
$products = [
["name" => "Laptop", "price" => 1200, "category" => "tech"],
["name" => "Mouse", "price" => 25, "category" => "tech"],
["name" => "Desk", "price" => 300, "category" => "furniture"],
["name" => "Chair", "price" => 150, "category" => "furniture"],
];
// Several conditions at once
$cheapTech = array_filter($products, fn($p) => $p["category"] === "tech" && $p["price"] < 500);
echo implode(", ", array_column($cheapTech, "name")) . "\n";
// Match any of several values
$wanted = ["Desk", "Mouse"];
$selected = array_filter($products, fn($p) => in_array($p["name"], $wanted, true));
echo implode(", ", array_column($selected, "name")) . "\n";
Output:
Mouse Mouse, Desk
4. Filter by key, or by key and value
<?php
$data = ["id" => 7, "name" => "Alice", "password" => "secret", "email" => "[email protected]"];
$allowed = ["id", "name", "email"];
$public = array_filter($data, fn($key) => in_array($key, $allowed, true), ARRAY_FILTER_USE_KEY);
print_r($public);
$both = array_filter([10, 20, 30, 40], fn($value, $key) => $key > 0 && $value < 40, ARRAY_FILTER_USE_BOTH);
print_r($both);
Output:
Array
(
[id] => 7
[name] => Alice
[email] => [email protected]
)
Array
(
[1] => 20
[2] => 30
)
Common mistakes and gotchas
- Gaps in keys: filtered arrays keep their keys, so
$result[0]may not exist andjson_encode()outputs an object. Usearray_values(). - "0" is removed: without a callback, the string "0" is falsy and disappears. Pass
'strlen'orfn($v) => $v !== ''to remove only empty strings. - Argument order: the array comes first, then the callback (the reverse of
array_map()).