You can use array_filter in PHP to remove unwanted data from arrays. It works with a custom callback or default rules.
Table of Content
Understand the array_filter Function in PHP
The array_filter
function removes elements from an array based on a given test. This function checks each element and keeps only those that pass the test.
Here is the basic syntax:
$result = array_filter($array, callback, mode);
- $array: the source array.
- callback: optional callable to test each value.
- mode: optional flag to pass keys as well.
The array_filter
keeps the original keys by default, while the filtered array will have the same keys as the source array.
A callback is a function you pass to array_filter
. PHP calls it on each element and expects it to return true
for values to keep and false
for values to remove.
The array_filter
removes all elements that evaluate to false
without a callback.
Here is an example:
function isEven($num) {
return $num % 2 === 0;
}
The common cases:
- Developers use
array_filter
for data validation to clean arrays. - You can remove null values or false entries. Also, allows you to ignore empty strings or keep specific matches based on rules.
You can also use anonymous functions inside array_filter
for inline tests. This avoids the need for separate named functions.
Here is an example:
$nums = [1, 2, 3, 4, 5];
$result = array_filter($nums, function($value) {
return $value > 3;
});
print_r($result);
This keeps numbers greater than 3. Here is the output:
Array
(
[3] => 4
[4] => 5
)
Use the array_filter with associative arrays
The array_filter
works with associative arrays just like with indexed arrays. You can also pass the ARRAY_FILTER_USE_KEY
flag to filter by keys.
For example:
$users = [ 'david' => 25, 'hala' => 17, 'carol' => 30 ];
$adults = array_filter($users, function($age) {
return $age >= 18;
});
print_r($adults);
This keeps users with an age of 18 or older. The output:
Array
(
[david] => 25
[carol] => 30
)
Here is another example with mode ARRAY_FILTER_USE_KEY:
$data = [ 'first' => 10, 'second' => 20, 'third' => 5 ];
$result = array_filter($data, function($key) {
return $key !== 'second';
}, ARRAY_FILTER_USE_KEY);
print_r($result);
This keeps all items except the one with the key second
. Here is the output:
Array
(
[first] => 10
[third] => 5
)
Examples of array_filter in PHP
Filter Odd Numbers:
$nums = [1, 2, 3, 4, 5];
$odds = array_filter($nums, function($value) {
return $value % 2 === 1;
});
print_r($odds);
This keeps values that return a remainder of 1 when divided by 2. The output:
Array
(
[0] => 1
[2] => 3
[4] => 5
)
Remove Empty Values from Array:
$items = ['apple', '', 'banana', null, 'cherry'];
$result = array_filter($items);
print_r($result);
This removes all empty or null values and keeps only valid strings. Here is the output:
Array
(
[0] => apple
[2] => banana
[4] => cherry
)
Filter by Both Keys and Values:
$records = [ 'user1' => 100, 'user2' => 50, 'admin' => 200 ];
$result = array_filter($records, function($value, $key) {
return $value > 80 && $key !== 'admin';
}, ARRAY_FILTER_USE_BOTH);
print_r($result);
This keeps users with scores above 80 but excludes the admin
:
Array
(
[user1] => 100
)
Advanced Filtering with External Data:
$allowed = ['a', 'c'];
$data = [ 'a' => 10, 'b' => 20, 'c' => 30 ];
$result = array_filter($data, function($key) use ($allowed) {
return in_array($key, $allowed);
}, ARRAY_FILTER_USE_KEY);
print_r($result);
This keeps only the keys listed in the $allowed
array:
Array
(
[a] => 10
[c] => 30
)
Wrapping Up
In this article, you learned how to use array_filter
with callbacks and default rules. You also saw how to handle associative arrays and keep keys intact.
Here is a quick recap:
array_filter
removes unwanted values.- Works with callbacks or default rules.
- Supports associative arrays.
- Keeps original keys.
FAQs
How to use php array_filter with a callback function?
$result = array_filter($data, function($value) {
return $value > 1;
});
This code returns values greater than 3 from the array. The callback decides which items remain.Can array_filter work without a callback?
$data = [0, 1, false, 2, '', 3];
$result = array_filter($data, function($value) {
return $value > 3;
});
print_r($result);
Without a callback, php array_filter removes false, null, 0, empty strings, and false values from the array.How to preserve array keys in php array_filter?
$data = ["a" => 1, "b" => 2, "c" => 3];
$result = array_filter($data, function($value) {
return $value > 3;
});
print_r($result);
php array_filter keeps the original array keys by default when filtering values.Similar Reads
If you are working with PHP and need a way to confirm if something is indeed a file, the is_file function will…
The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…
There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…
The PHP named arguments are the names of the arguments through which the values are passed, allowing you to add…
PHP static method lets you call functions without an object. In this article, we will cover the following topics: The…
You can use your Raspberry Pi as a personal web server or tool that runs in your home. You do…
In this tutorial, you will learn how to install PHP on your Operating system such as Ubuntu, Windows, or macOS.…
The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…
PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article,…
PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…