PHP array_filter() - Complete Guide with Examples
Mahesh Waghmare The array_filter() function is one of PHP’s most useful array functions. It allows you to filter array elements based on a callback function, making it essential for data processing, validation, and transformation tasks.
This comprehensive guide covers everything you need to know about array_filter(), from basic usage to advanced patterns and performance optimization.
Introduction to array_filter()
array_filter() filters elements of an array using a callback function. It returns a new array containing only the elements for which the callback returns true.
Key Characteristics:
- Preserves original array keys (unless using ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH)
- Returns new array (doesn’t modify original)
- Works with indexed and associative arrays
- Can use callback function or rely on truthiness
Common Use Cases:
- Remove empty values
- Filter by condition
- Data validation
- Remove specific values
- Extract matching elements
Syntax and Parameters
Function Signature
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Parameters
$array (required):
- The array to filter
- Can be indexed or associative
$callback (optional):
- Callback function to test each element
- If omitted, filters out falsy values
- Should return
trueto keep element,falseto remove
$mode (optional):
0(default): Pass value to callbackARRAY_FILTER_USE_KEY: Pass key to callbackARRAY_FILTER_USE_BOTH: Pass both value and key to callback
Return Value
Returns a new array with filtered elements, preserving keys.
Basic Usage Examples
Filter Empty Values
Without Callback (filters falsy values):
$array = [1, 0, '', 'hello', null, false, 'world', []];
$filtered = array_filter($array);
// Result: [0 => 1, 3 => 'hello', 6 => 'world']
// Note: Keys are preserved, 0 and false are removed
Common Falsy Values Removed:
falsenull0(integer)'0'(string)''(empty string)[](empty array)
Filter by Value
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Keep only even numbers
$even = array_filter($numbers, function($value) {
return $value % 2 === 0;
});
// Result: [1 => 2, 3 => 4, 5 => 6, 7 => 8, 9 => 10]
Filter Associative Arrays
$users = [
'john' => ['age' => 25, 'active' => true],
'jane' => ['age' => 30, 'active' => false],
'bob' => ['age' => 20, 'active' => true],
];
// Keep only active users
$active = array_filter($users, function($user) {
return $user['active'] === true;
});
Remove Specific Values
$data = ['apple', 'banana', '', 'orange', null, 'grape', ''];
// Remove empty strings
$cleaned = array_filter($data, function($value) {
return $value !== '';
});
// Result: [0 => 'apple', 1 => 'banana', 3 => 'orange', 5 => 'grape']
Using Callback Functions
Named Functions
function isEven($value) {
return $value % 2 === 0;
}
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, 'isEven');
Anonymous Functions
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function($value) {
return $value % 2 === 0;
});
Using External Variables (Closure)
$minAge = 18;
$users = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 16],
['name' => 'Bob', 'age' => 30],
];
$adults = array_filter($users, function($user) use ($minAge) {
return $user['age'] >= $minAge;
});
Class Methods
class UserFilter {
private $minAge;
public function __construct($minAge) {
$this->minAge = $minAge;
}
public function isAdult($user) {
return $user['age'] >= $this->minAge;
}
}
$filter = new UserFilter(18);
$adults = array_filter($users, [$filter, 'isAdult']);
Arrow Functions (PHP 7.4+)
Arrow functions provide concise syntax:
$numbers = [1, 2, 3, 4, 5];
// Traditional anonymous function
$even1 = array_filter($numbers, function($n) {
return $n % 2 === 0;
});
// Arrow function (PHP 7.4+)
$even2 = array_filter($numbers, fn($n) => $n % 2 === 0);
With External Variables:
$minAge = 18;
// Arrow functions automatically capture variables
$adults = array_filter($users, fn($user) => $user['age'] >= $minAge);
Common Patterns
Filter by Key
Use ARRAY_FILTER_USE_KEY:
$data = [
'user_1' => 'John',
'admin_1' => 'Admin',
'user_2' => 'Jane',
'guest_1' => 'Guest',
];
// Keep only user_* keys
$users = array_filter($data, function($key) {
return strpos($key, 'user_') === 0;
}, ARRAY_FILTER_USE_KEY);
Filter by Both Key and Value
Use ARRAY_FILTER_USE_BOTH:
$data = [
'user_1' => 'John',
'admin_1' => 'Admin',
'user_2' => '',
'user_3' => 'Jane',
];
// Keep user_* keys with non-empty values
$valid = array_filter($data, function($value, $key) {
return strpos($key, 'user_') === 0 && $value !== '';
}, ARRAY_FILTER_USE_BOTH);
Reindex Array After Filtering
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
// Reindex
$even = array_values($even);
// Result: [0 => 2, 1 => 4] (keys reset to 0, 1, 2...)
Filter and Transform
$numbers = [1, 2, 3, 4, 5];
// Filter and square
$squared = array_map(function($n) {
return $n * $n;
}, array_filter($numbers, fn($n) => $n % 2 === 0));
Advanced Examples
Complex Filtering
$products = [
['name' => 'Laptop', 'price' => 1000, 'stock' => 5, 'category' => 'electronics'],
['name' => 'Phone', 'price' => 500, 'stock' => 0, 'category' => 'electronics'],
['name' => 'Book', 'price' => 20, 'stock' => 10, 'category' => 'books'],
];
// Filter: electronics, in stock, price < 800
$filtered = array_filter($products, function($product) {
return $product['category'] === 'electronics'
&& $product['stock'] > 0
&& $product['price'] < 800;
});
Multiple Conditions
function createFilter($conditions) {
return function($item) use ($conditions) {
foreach ($conditions as $key => $value) {
if (!isset($item[$key]) || $item[$key] !== $value) {
return false;
}
}
return true;
};
}
$filter = createFilter(['category' => 'electronics', 'stock' => ['>', 0]]);
$result = array_filter($products, $filter);
Filter Nested Arrays
$data = [
'users' => [
['id' => 1, 'active' => true],
['id' => 2, 'active' => false],
],
'posts' => [
['id' => 1, 'published' => true],
['id' => 2, 'published' => false],
],
];
$filtered = array_map(function($items) {
return array_filter($items, fn($item) =>
($item['active'] ?? $item['published'] ?? false) === true
);
}, $data);
Remove Duplicates After Filtering
$numbers = [1, 2, 2, 3, 3, 4, 5];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
$unique = array_unique($even);
Performance Considerations
Large Arrays
For large arrays, consider:
// Less efficient: multiple passes
$filtered1 = array_filter($array, fn($x) => $x > 0);
$filtered2 = array_filter($filtered1, fn($x) => $x < 100);
// More efficient: single pass
$filtered = array_filter($array, fn($x) => $x > 0 && $x < 100);
Early Returns in Callbacks
// Optimize callbacks with early returns
$filtered = array_filter($items, function($item) {
// Early return for common case
if (empty($item)) {
return false;
}
// Expensive checks only if needed
return expensiveCheck($item);
});
Memory Usage
array_filter() creates a new array. For very large arrays:
// If memory is concern, use generator
function filterGenerator($array, $callback) {
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
yield $key => $value;
}
}
}
Best Practices
- Use Arrow Functions for simple filters (PHP 7.4+)
- Reindex Arrays if sequential keys are needed
- Combine Conditions in single filter when possible
- Document Complex Callbacks with comments
- Test Edge Cases (empty arrays, null values)
Conclusion
array_filter() is essential for:
- Removing unwanted values
- Data validation
- Conditional extraction
- Array processing
Key Takeaways:
- Use without callback to remove falsy values
- Use callbacks for custom filtering logic
- Preserve keys or reindex as needed
- Combine with other array functions
- Consider performance for large arrays
Mastering array_filter() will make your PHP code more expressive and efficient.
Written by Mahesh Waghmare
I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.
Follow on Twitter →