array_filter() keeps only the items that pass a test. Your function returns true to keep an item and false to drop it.
<?php
$ages = [12, 25, 17, 40, 8];
$adults = array_filter($ages, fn($age) => $age >= 18);
print_r($adults);
Array
(
[1] => 25
[3] => 40
)
Keys are preserved
Look at the keys above: 1 and 3. array_filter() keeps the original keys. If you need a clean list, wrap the result in array_values().
<?php
$ages = [12, 25, 17, 40, 8];
$adults = array_values(array_filter($ages, fn($age) => $age >= 18));
print_r($adults);
Array
(
[0] => 25
[1] => 40
)
No callback: remove empty values
Without a function, array_filter() removes every falsy value.
<?php
$input = ["php", "", "web", null, "0", "css"];
print_r(array_filter($input));
Array
(
[0] => php
[2] => web
[5] => css
)
Notice that "0" was removed too, because it is falsy. If "0" is valid data, use a callback: fn($v) => $v !== "" && $v !== null.
Filter records
<?php
$products = [
["name" => "Pen", "price" => 12, "stock" => 100],
["name" => "Bag", "price" => 799, "stock" => 0],
["name" => "Book", "price" => 250, "stock" => 8],
];
$available = array_filter($products, fn($p) => $p["stock"] > 0);
echo implode(", ", array_column($available, "name"));
Pen, Book
Use the key in the test
<?php
$data = ["name" => "Isha", "password" => "secret", "email" => "i@example.com"];
$safe = array_filter($data, fn($key) => $key !== "password", ARRAY_FILTER_USE_KEY);
print_r($safe);
Array
(
[name] => Isha
[email] => i@example.com
)
ARRAY_FILTER_USE_BOTH passes the value and the key to your function.
Combine with the outside world
An arrow function sees outside variables, so filtering by a user’s input is simple.
<?php
$products = [
["name" => "Pen", "price" => 12],
["name" => "Bag", "price" => 799],
];
$maxPrice = 100;
$cheap = array_filter($products, fn($p) => $p["price"] <= $maxPrice);
echo count($cheap);
1
PHP 8.4 extras
PHP 8.4 added array_find(), array_find_key(), array_any() and array_all(). They answer common questions without building a whole new array.
<?php
$hasAdult = array_any($ages, fn($a) => $a >= 18); // true or false
$allAdults = array_all($ages, fn($a) => $a >= 18); // true or false
Those need PHP 8.4. On earlier versions, use array_filter() and count().
Exercise: even numbers
Given [1, 2, 3, 4, 5, 6], keep only the even numbers and print them as a clean list.
Show a possible solution
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$even = array_values(array_filter($numbers, fn($n) => $n % 2 === 0));
echo implode(", ", $even);
2, 4, 6