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 sizeof: How to Count Elements in Arrays with Examples

The sizeof function in PHP exists to help developers know how many items an array holds. Understand the sizeof Function…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

Mastering PHP’s Do-While Loop: Examples and Explanation

The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

PHP strlen Function: How It Works with Strings

Developers needed a way to check the length of a string, so the strlen function was introduced to handle this…

PHP Data Types: Understanding the 10 Primitive Types

The whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these…

PHP file_exists: Check File and Directory Existence

Whether you are just trying to keep your app from crashing or making sure your users’ uploads don’t accidentally overwrite…

PHP error_log Function: How It Works with Examples

Sometimes things go wrong when PHP runs the code. So, you need to know the reasons for this error to…

PHP Integers Guide: Types, Limits, and Conversions

You use integers (int) in PHP to count items, set page numbers, handle IDs, and manage loop counters. In this…

PHP strtolower Function: Convert Strings to Lowercase

Text does not always look the same. One word may appear in lowercase, another in uppercase. You want both to…

PHP SimpleXML: Work with XML in Examples

PHP SimpleXML - invented for you to work with XML. Way leaner, quicker to get up. it's already integrated directly…

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.