When working with PHP arrays, you often need to keep only the elements that meet a specific condition. For example, you might want to find products that are in stock, remove unwanted values, or select numbers above a certain limit.
The array_filter() function makes these tasks easier by filtering array elements using a callback function.
In this guide, you'll learn how to filter values and keys, handle empty values, and use array_filter() in a practical application.
What Is array_filter() in PHP?
The array_filter() function creates a new array containing only the elements that pass a specified condition.
Its syntax is:
array_filter(
array $array,
?callable $callback = null,
int $mode = 0
): array
The function accepts three parameters:
$array— The original array to filter.$callback— An optional function that determines which elements to keep.$mode— Controls whether the callback receives values, keys, or both.
If the callback returns a truthy value, the element is kept. Otherwise, it is removed from the result.
The original array remains unchanged, and its keys are preserved.
Example 1: Filtering Array Values
Let's keep only numbers greater than five.
<?php
$numbers = [3, 8, 2, 12, 5];
$result = array_filter(
$numbers,
fn(int $number): bool => $number > 5
);
print_r($result);
Output:
Array
(
[1] => 8
[3] => 12
)
The callback checks each number. Only 8 and 12 satisfy the condition.
Notice that the original numeric keys are preserved. If you need consecutive indexes starting at zero, use array_values():
$result = array_values($result);
Example 2: Removing Empty Values
You can call array_filter() without a callback. In this case, PHP removes values considered empty or falsy.
<?php
$values = [
"PHP",
"",
null,
0,
"JavaScript",
false
];
$result = array_filter($values);
print_r($result);
Output:
Array
(
[0] => PHP
[4] => JavaScript
)
Without a callback, values such as 0, "0", false, null, empty strings, and empty arrays are removed.
Important: If zero or false is a valid value in your application, don't rely on the default filtering behavior.
For example, to remove only null values:
$result = array_filter(
$values,
fn($value): bool => $value !== null
);
Filtering Array Keys
By default, the callback receives each array value. You can change this behavior using ARRAY_FILTER_USE_KEY.
<?php
$stock = [
"Keyboard" => 12,
"Mouse" => 0,
"Monitor" => 5
];
$result = array_filter(
$stock,
fn(string $key): bool =>
str_starts_with($key, "M"),
ARRAY_FILTER_USE_KEY
);
print_r($result);
Output:
Array
(
[Mouse] => 0
[Monitor] => 5
)
The callback examines product names rather than quantities. The str_starts_with() function used here requires PHP 8.0 or later.
Filtering by Both Keys and Values
Use ARRAY_FILTER_USE_BOTH when your condition depends on the array key and its value.
Using the $stock array from the previous example:
$result = array_filter(
$stock,
fn(int $quantity, string $name): bool =>
str_starts_with($name, "M")
&& $quantity > 0,
ARRAY_FILTER_USE_BOTH
);
print_r($result);
Output:
Array
(
[Monitor] => 5
)
Only the Monitor matches both conditions: its name starts with M, and its quantity is greater than zero.
Remember that with ARRAY_FILTER_USE_BOTH, the callback receives the value first, followed by the key.
Practical Example: Filtering Available Products
Imagine you're building an online store. Each product has a name, a stock quantity, and an active status.
We want to display only products that are active and currently available.
Create a file named available-products.php:
<?php
declare(strict_types=1);
$products = [
[
"name" => "Keyboard",
"stock" => 12,
"active" => true
],
[
"name" => "Mouse",
"stock" => 0,
"active" => true
],
[
"name" => "Monitor",
"stock" => 5,
"active" => true
],
[
"name" => "Webcam",
"stock" => 8,
"active" => false
]
];
// Keep active products with available stock.
$availableProducts = array_filter(
$products,
static fn(array $product): bool =>
$product["active"] === true
&& $product["stock"] > 0
);
// Display available products.
echo "<h2>Available Products</h2>";
echo "<ul>";
foreach ($availableProducts as $product) {
$message = $product["name"]
. " - "
. $product["stock"]
. " in stock";
echo "<li>" . htmlspecialchars(
$message,
ENT_QUOTES,
"UTF-8"
) . "</li>";
}
echo "</ul>";
Browser output:
Available Products
Keyboard - 12 in stock
Monitor - 5 in stock
The Mouse is excluded because it has no stock. The Webcam is excluded because it is inactive.
The original product list remains unchanged, allowing the application to use it for other operations.
This example uses predefined, correctly structured product data. Validate incoming records before passing them to a typed callback.
array_filter() vs Related Functions
| Function | Purpose |
|---|---|
array_filter() |
Returns elements that satisfy a condition. |
array_map() |
Transforms array elements using a callback. |
array_find() |
Returns the first matching value (PHP 8.4+). |
array_any() |
Checks whether at least one element matches (PHP 8.4+). |
Use array_filter() when you need all matching elements, rather than a transformed array or a single matching result.
Common Mistakes
- Expecting automatic reindexing: Array keys are preserved. Use
array_values()when consecutive numeric indexes are required. - Removing valid values accidentally: Omitting the callback also removes zero and
false. - Confusing callback arguments: With
ARRAY_FILTER_USE_BOTH, the value comes before the key. - Expecting the original array to change: Assign the returned filtered array to a variable.
- Modifying the input array inside the callback: Avoid adding or removing entries from the array being filtered because the behavior is undefined.
Key Takeaways
array_filter()creates a new array containing elements that pass a condition.- Callbacks allow you to define custom filtering rules.
- Without a callback, PHP removes values considered empty.
- Use
ARRAY_FILTER_USE_KEYto filter by keys. - Use
ARRAY_FILTER_USE_BOTHto examine values and keys together. - Original array keys are preserved in the result.
The array_filter() function is a useful tool for selecting relevant data from PHP arrays. Whether you're filtering products, cleaning input, or working with structured records, it helps keep your code readable and organized.
For additional details, see the official PHP array_filter() documentation.