Skip to content

PHP Tutorial Arrays

Filtering Arrays

Lesson 126 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

array_filter() keeps only the items that pass a test. Your function returns true to keep an item and false to drop it.

index.php
PHP
<?php
$ages = [12, 25, 17, 40, 8];

$adults = array_filter($ages, fn($age) => $age >= 18);

print_r($adults);
Output
OUTPUT
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().

index.php
PHP
<?php
$ages = [12, 25, 17, 40, 8];

$adults = array_values(array_filter($ages, fn($age) => $age >= 18));

print_r($adults);
Output
OUTPUT
Array
(
    [0] => 25
    [1] => 40
)

No callback: remove empty values

Without a function, array_filter() removes every falsy value.

index.php
PHP
<?php
$input = ["php", "", "web", null, "0", "css"];

print_r(array_filter($input));
Output
OUTPUT
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

index.php
PHP
<?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"));
Output
OUTPUT
Pen, Book

Use the key in the test

index.php
PHP
<?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);
Output
OUTPUT
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.

index.php
PHP
<?php
$products = [
    ["name" => "Pen", "price" => 12],
    ["name" => "Bag", "price" => 799],
];
$maxPrice = 100;

$cheap = array_filter($products, fn($p) => $p["price"] <= $maxPrice);

echo count($cheap);
Output
OUTPUT
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.

index.php
PHP
<?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
index.php
PHP
<?php
$numbers = [1, 2, 3, 4, 5, 6];

$even = array_values(array_filter($numbers, fn($n) => $n % 2 === 0));

echo implode(", ", $even);
Output
OUTPUT
2, 4, 6