PHP array_filter: How to Filter Array Values with Examples

php array filter

You can use array_filter in PHP to remove unwanted data from arrays. It works with a custom callback or default rules.

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

PHP File Inclusion: require, include, require_once, include_once

PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…

PHP Associative Array: Optimal Data Organization

The PHP associative array is a structured collection wherein data elements are organized into lists or groups. Each element is…

PHP array_intersect Function: How it Works with Examples

The PHP array_intersect function finds common values in arrays and returns matches as a new array. Understand the array_intersect in…

PHP Strings: Types, Variables & Syntax Tips

If you start working with PHP, it won't take you that long to figure out that strings are everywhere. Besides…

PHP fopen: Understanding fopen Modes

PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we…

PHP break Statement: How to Exit a Loop

The PHP break statement helps in controlling the flow of loop work. It gives you a way to stop a…

PHP cURL: HTTP Requests and Responses in PHP

In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the…

IF-Else: Executes the IF-Else Statement in PHP

Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

Understanding the PHP Enumerable

Actually, the PHP enumerable is a new feature of 8.1 which allows you to define a new type. This feature…

PHP array_rand() Function: Usage & Examples

The array_rand() is a helper function in PHP that makes it easier when dealing with arrays; you can just pull…

Previous Article

HTML Document Structure: How to Create DOCTYPE in HTML

Next Article

PHP array_push Function: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.