Table of contents
1.
Introduction
2.
Definition and Usage  
3.
Syntax
4.
Parameters
5.
Return Value
6.
Examples
6.1.
Example 1: Filtering Even Numbers
6.2.
Example 2: Removing Empty Strings
6.3.
Example 3: Using the `$mode` Parameter  
6.4.
Example 4: Filtering Without a Callback  
6.5.
Example 5: Using ARRAY_FILTER_USE_KEY
7.
Common Use Cases and Best Practices for `array_filter()`  
7.1.
Use Case 1: Filtering Data from User Input  
7.2.
Use Case 2: Filtering Associative Arrays  
7.3.
Use Case 3: Combining `array_filter()` with Other Array Functions  
8.
Best Practices  
9.
PHP Version
10.
PHP Changelog
11.
Frequently Asked Questions
11.1.
What happens if no callback function is provided?
11.2.
Does array_filter() reindex the array?
11.3.
Can array_filter() be used with associative arrays?
12.
Conclusion
Last Updated: Feb 16, 2025
Easy

PHP array_filter() Function

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The PHP array_filter() function is used to filter elements of an array based on a custom callback function. It allows developers to remove unwanted values while keeping only those that meet specific conditions. This function is especially useful for data validation and processing in PHP applications.

PHP array_filter() Function

In this article, we will cover its syntax, parameters, return values, examples, PHP versions, and changelog details.

Definition and Usage  

The `array_filter()` function in PHP is used to filter elements of an array based on a callback function. It iterates through each element of the array & applies the callback function to it. If the callback function returns `true`, the element is included in the resulting array. If it returns `false`, the element is excluded.  

Syntax

The syntax of the array_filter() function is:

array array_filter(array $array, callable|null $callback = null, int $mode = 0)

 

Here,

  • $array: The input array that needs to be filtered.
     
  • $callback: (Optional) A function that decides whether an element should be kept or removed.
     
  • $mode: (Optional) Defines whether to pass only values or both keys and values to the callback function.

If no callback function is provided, array_filter() removes all elements that evaluate to false (such as 0, null, false, and empty strings).

Parameters

  1. $array (Required) – The input array from which elements will be filtered.
     
  2. $callback (Optional) – A function that determines whether an element should be included in the result. If null, the function removes all elements that evaluate to false.
     
  3. $mode (Optional, Default = 0) – Specifies how the callback function will be used:
    • 0 (default) – Only values are passed to the callback function.
       
    • ARRAY_FILTER_USE_KEY – Only array keys are passed to the callback function.
       
    • ARRAY_FILTER_USE_BOTH – Both keys and values are passed to the callback function.

Return Value

The array_filter() function returns a new array containing elements that satisfy the condition defined in the callback function. The array keys are preserved but not reindexed.

Examples

Example 1: Filtering Even Numbers

function isEven($num) {
    return $num % 2 == 0;
}

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenNumbers = array_filter($numbers, "isEven");

print_r($evenNumbers);
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)

Example 2: Removing Empty Strings

$strings = ["Hello", "", "PHP", " ", "World", null, "!"];
$filteredStrings = array_filter($strings);

print_r($filteredStrings);
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [0] => Hello
    [2] => PHP
    [4] => World
    [6] => !
)

Example 3: Using the `$mode` Parameter  

The `$mode` parameter allows you to pass both the key & value to the callback function. Let’s see how you can use it:  

<?php  
$associativeArray = [  
    'a' => 1,  
    'b' => 0,  
    'c' => 3,  
    'd' => '',  
    'e' => 5  
];  

// Callback function to filter based on both key and value  
function filterKeyValue($value, $key) {  
    return $value !== '' && $key !== 'b';  
}  

// Filter the array with ARRAY_FILTER_USE_BOTH flag  
$filteredArray = array_filter($associativeArray, 'filterKeyValue', ARRAY_FILTER_USE_BOTH);  

// Print the result  
print_r($filteredArray);  
?>  
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [a] => 1  
    [c] => 3  
    [e] => 5  
)  

Example 4: Filtering Without a Callback  

If you don’t provide a callback function, `array_filter()` removes all "falsey" values from the array. For  example:  

<?php  
$mixedValues = [0, 1, false, 2, '', 3, null, 4, '0', 5];  


// Filter the array without a callback  
$filteredValues = array_filter($mixedValues);  


// Print the result  
print_r($filteredValues);  
?>  
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [1] => 1  
    [3] => 2  
    [5] => 3  
    [7] => 4  
    [9] => 5  
)  


In this case, all "falsey" values like `0`, `false`, `""`, `null`, & `'0'` are removed from the array.  

Here, the callback function filters out elements where the value is an empty string or the key is `'b'`.  

Example 5: Using ARRAY_FILTER_USE_KEY

$array = [
    "a" => 10,
    "b" => 20,
    "c" => 30
];

$filteredKeys = array_filter($array, function ($key) {
    return $key !== "b";
}, ARRAY_FILTER_USE_KEY);

print_r($filteredKeys);
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [a] => 10
    [c] => 30
)

Common Use Cases and Best Practices for `array_filter()`  

The `array_filter()` function is versatile & can be used in various scenarios to make your code cleaner & more efficient. 

Now let’s discuss some of the common use cases & best practices to help you get the most out of this function.  

Use Case 1: Filtering Data from User Input  

When working with user input, you often need to sanitize or filter data. For example, you might want to remove empty values from a form submission.  

<?php  
// Simulated user input from a form  
$userInput = [  
    'name' => 'John Doe',  
    'email' => '',  
    'age' => '25',  
    'city' => null,  
    'country' => 'USA'  
];  


// Filter out empty values  
$filteredInput = array_filter($userInput);  


// Print the result  
print_r($filteredInput);  
?>  
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [name] => John Doe  
    [age] => 25  
    [country] => USA  
)  


In this example, `array_filter()` removes empty values like `""` & `null`, ensuring only valid data is processed.  

Use Case 2: Filtering Associative Arrays  

You can use `array_filter()` to filter associative arrays based on specific conditions. For instance, let’s filter an array of products to find items with a price greater than 50.  

<?php  
$products = [  
    ['name' => 'Laptop', 'price' => 1200],  
    ['name' => 'Mouse', 'price' => 25],  
    ['name' => 'Keyboard', 'price' => 60],  
    ['name' => 'Monitor', 'price' => 300]  
];  


// Callback function to filter products with price > 50  
function filterExpensiveProducts($product) {  
    return $product['price'] > 50;  
}  


// Filter the array  
$expensiveProducts = array_filter($products, 'filterExpensiveProducts');  


// Print the result  
print_r($expensiveProducts);  
?>  
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [0] => Array  
        (  
            [name] => Laptop  
            [price] => 1200  
        )  

    [2] => Array  
        (  
            [name] => Keyboard  
            [price] => 60  
        )  

    [3] => Array  
        (  
            [name] => Monitor  
            [price] => 300  
        )  
)  


Here, the callback function checks if the product price is greater than 50, & `array_filter()` returns only those products.  

Use Case 3: Combining `array_filter()` with Other Array Functions  

You can combine `array_filter()` with other array functions like `array_map()` or `array_reduce()` for more complex operations. For example, let’s filter an array of numbers & then calculate their sum.  

<?php  
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];  

// Filter out even numbers  
$oddNumbers = array_filter($numbers, function($number) {  
    return $number % 2 !== 0;  
});  

// Calculate the sum of odd numbers  
$sum = array_reduce($oddNumbers, function($carry, $number) {  
    return $carry + $number;  
}, 0);  

// Print the result  
echo "Sum of odd numbers: $sum";  
?>  
You can also try this code with Online PHP Compiler
Run Code


Output:  

Sum of odd numbers: 25  


In this example, `array_filter()` removes even numbers, & `array_reduce()` calculates the sum of the remaining odd numbers.  

Best Practices  


1. Use Anonymous Functions for Simple Filters: If the filtering logic is simple, use anonymous functions (closures) instead of defining a separate function. This keeps your code concise.  

   $filteredArray = array_filter($array, function($value) {  
       return $value > 10;  
   });  


2. Preserve Keys When Needed: By default, `array_filter()` preserves the keys of the original array. If you want to reindex the array, use `array_values()` after filtering.  

   $filteredArray = array_values(array_filter($array));  


3. Combine with Other Array Functions: As shown earlier, combining `array_filter()` with functions like `array_map()` or `array_reduce()` can help you perform complex operations efficiently. 

PHP Version

The array_filter() function has been available since PHP 4.0.6 and is supported in all modern PHP versions, including PHP 5, PHP 7, and PHP 8.

PHP Changelog

  • PHP 5.6.0 – Added the $mode parameter.
     
  • PHP 4.0.6 – Initial introduction of array_filter() function.

Frequently Asked Questions

What happens if no callback function is provided?

If no callback function is provided, array_filter() will remove all elements that evaluate to false (0, false, null, "", etc.).

Does array_filter() reindex the array?

No, array_filter() preserves the original keys. If needed, you can use array_values() to reset the keys.

Can array_filter() be used with associative arrays?

Yes, array_filter() works with both indexed and associative arrays.

Conclusion

In this article, we learned about the PHP array_filter() function, which helps filter elements of an array using a callback function. This function is useful for removing unwanted values and processing data efficiently. Understanding how to use array_filter() allows developers to write cleaner and more optimized code, improving both performance and readability in PHP applications.

Live masterclass