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 array_change_key_case: Change Array Key Cases

The array_change_key_case function in PHP changes all array keys to lowercase or uppercase for consistent data use. Understand the array_change_key_case…

PHP Arrow Functions: Understanding “fn” Syntax

Arrow functions were introduced in PHP 7.4. They offer you a way to write simple operations, such as calculations, filters,…

PHP filter_id Function: How to Retrieve PHP Filter IDs

Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

PHP Switch | How the Switch Statement Works in PHP

The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

PHP array_fill Function: Fill Array with Same Value

You can use the array_fill function in PHP when you must fill an array with one value. You may want…

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

Learn How to Insert Documents in MongoDB Using PHP

Inserting documents into your MongoDB collections is one of the most basic but important tasks when working with PHP. In…

PHP mail() Function: A Complete Guide

PHP mail() is a great built-in function for sending an email directly from your script for account confirmations, password resets, or sending notifications.…

PHP $GLOBALS: Access Global Variables with Examples

When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…

PHP array_diff_uassoc: How to Compare Arrays with Keys

PHP array_diff_uassoc compares arrays by values and keys. You can also pass a custom function to compare keys in your…

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.