PHP array_filter() - Filter Array Elements
SEO Description: Learn PHP array_filter() function. Filter array elements using callback functions to remove unwanted values from arrays.
SEO Keywords: PHP array_filter, filter array PHP, array filtering, PHP array callback filter, remove array values, PHP array filter function
Introduction
Working with arrays is fundamental in PHP, especially when you need to manipulate and refine large datasets. The array_filter() function provides a powerful, flexible way to filter array elements using callbacks, allowing developers to remove unwanted or undesired values easily.
This tutorial is designed for PHP developers looking to master array_filter() to process arrays efficiently and elegantly.
Prerequisites
- Basic knowledge of PHP syntax
- Understanding of PHP arrays (indexed and associative)
- Familiarity with anonymous functions (PHP 5.3+ recommended)
Setup Steps
Before experimenting with array_filter(), ensure you have a PHP environment such as:
- PHP installed locally (version 5.3 or later recommended)
- A text editor or IDE (Visual Studio Code, PHPStorm, Sublime Text, etc.)
- Optional: A local web server (XAMPP, MAMP, WAMP) or a command line terminal
Open your PHP file and include sample data to execute array_filter() examples.
What is array_filter()?
The array_filter() function filters elements of an array using a callback function. It returns a new array containing elements for which the callback returns true. If no callback is provided, elements having a falsy value (e.g., false, 0, null, '') are removed.
Function Signature
array_filter(array $array, callable|null $callback = null, int $mode = 0): array
$array: The input array to be filtered.$callback: (optional) Function to use for testing each value. Returntrueto keep the element,falseto remove it.$mode: (optional) Flag determining whether to pass only the value (ARRAY_FILTER_USE_VALUE), key (ARRAY_FILTER_USE_KEY), or both (ARRAY_FILTER_USE_BOTH) to the callback (available from PHP 5.6).
Examples Explained
Example 1: Basic Filtering with Default Behavior
<?php
$input = [0, 1, 2, null, false, '', 3];
$result = array_filter($input);
print_r($result);
?>
Output:
Array
(
[1] => 1
[2] => 2
[6] => 3
)
Explanation: Without a callback, array_filter() removes falsy values like 0, null, false, and empty string from the array. Only values evaluated as true remain.
Example 2: Filtering Using a Callback (Keeping Even Numbers)
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$evenNumbers = array_filter($numbers, function($num) {
return $num % 2 === 0;
});
print_r($evenNumbers);
?>
Output:
Array
(
[1] => 2
[3] => 4
[5] => 6
)
Explanation: The callback checks for even numbers and returns true only for them. The filtered array contains only even numbers.
Example 3: Filtering Associative Arrays by Keys
<?php
$data = [
'apple' => 150,
'banana' => 100,
'cherry' => 75,
'date' => 120,
];
// Filter to keep only fruits with keys starting with 'b'
$filtered = array_filter($data, function($key) {
return strpos($key, 'b') === 0;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered);
?>
Output:
Array
(
[banana] => 100
)
Explanation: By using the ARRAY_FILTER_USE_KEY flag, the callback works on keys instead of values. The function keeps keys starting with 'b'.
Example 4: Filtering Using Both Keys and Values
<?php
$items = [
'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20,
];
$filtered = array_filter($items, function($value, $key) {
return $value > 10 && !in_array($key, ['d']);
}, ARRAY_FILTER_USE_BOTH);
print_r($filtered);
?>
Output:
Array
(
[c] => 15
)
Explanation: The callback filters elements where the value is greater than 10 and excludes the key 'd'. Using ARRAY_FILTER_USE_BOTH passes both key and value to the callback.
Best Practices
- Use clear and concise callbacks: Keep your callback functions simple and focused on one condition for maintainability.
- Preserve keys intentionally: By default,
array_filter()preserves original keys, which is useful in associative arrays. - Use
ARRAY_FILTER_USE_KEYorARRAY_FILTER_USE_BOTHonly when needed: This enhances flexibility but adds complexity. - Chain filtering carefully: You can chain multiple
array_filter()calls for complex filtering logic. - Performance: For large arrays, callbacks should be optimized for speed.
Common Mistakes
- Not understanding that keys are preserved by default can lead to unexpected array structure.
- Omitting the callback leads to removal only of falsy values, which may not be what you want.
- Ignoring that callback must return a boolean (or a value evaluated as boolean) to keep elements.
- Using
array_filter()with a callback that has side effects - callbacks should be pure functions. - Confusing filtering by keys and values and forgetting the
modeparameter.
Interview Questions
Junior Level
-
Q1: What does
array_filter()do if no callback is provided?
A: It removes elements with falsy values like false, null, 0, and empty strings. -
Q2: Does
array_filter()preserve keys by default?
A: Yes, keys are preserved in the returned array. -
Q3: How would you filter out all falsey elements from an array?
A: Callarray_filter($array)without a callback. -
Q4: Can
array_filter()be used with associative arrays?
A: Yes, it works with indexed and associative arrays. -
Q5: What type of argument does the callback receive by default?
A: The value of each element in the array.
Mid Level
-
Q1: How can you filter an array by its keys using
array_filter()?
A: By passingARRAY_FILTER_USE_KEYas the third argument and checking the key in the callback. -
Q2: Explain what
ARRAY_FILTER_USE_BOTHdoes.
A: It allows the callback to receive both value and key as arguments for filtering. -
Q3: Can the callback function change the array keys?
A: No, it only determines which elements are kept; keys stay the same. -
Q4: What will happen if callback returns a non-boolean value?
A: It is evaluated as boolean; truthy values keep the element, falsy remove it. -
Q5: Show a way to remove all empty strings from an array using
array_filter().
A: Use a callback likefunction($v) { return $v !== ''; }.
Senior Level
-
Q1: How can you use
array_filter()to emulate "find by pattern" behaviors in associative arrays?
A: UseARRAY_FILTER_USE_KEYto filter keys by matching a regex pattern inside the callback. -
Q2: Discuss performance considerations when using
array_filter()with large datasets.
A: Callback optimization is critical; avoid expensive operations per element and consider early returns. -
Q3: How would you implement a filter that depends on an external variable without causing unexpected behavior?
A: Use closures properly capturing variables or pass variables explicitly to avoid side effects. -
Q4: Is there a difference in behavior between filtering indexed vs. associative arrays?
A: Yes, keys are preserved, but indexed arrays may retain non-sequential keys, which can impact subsequent processing. -
Q5: Can
array_filter()be used to remove duplicates? Why or why not?
A: Not directly;array_filter()is for filtering based on a condition, whilearray_unique()is better suited for removing duplicates.
FAQ
Q: What PHP version introduced the mode parameter in array_filter()?
A: The mode parameter was introduced in PHP 5.6.
Q: Does array_filter() modify the original array?
A: No, it returns a new filtered array without modifying the input array.
Q: How do I reindex the array keys after filtering?
A: Use array_values() on the filtered array to reset keys to 0-based indexes.
Q: Can I pass a named function instead of an anonymous function as callback?
A: Yes, you can pass any callable including named functions, closures, or static methods.
Q: What happens if my callback unexpectedly returns null?
A: It will be treated as falsy and the corresponding element will be removed from the result.
Conclusion
The PHP array_filter() function is an essential tool for developers seeking to efficiently clean, extract, and manipulate arrays based on custom logic. By mastering callbacks and the optional filtering modes, you can build flexible, readable PHP code that handles arrays of any complexity.
Whether filtering values, keys, or both, remember to use best practices to keep your code simple and maintainable. Finally, always test edge cases to avoid common pitfalls when dealing with array filtering.
With 15+ years of experience processing arrays in PHP, harnessing array_filter() is a must-have skill for any PHP developer.