PHP
Filter Multidimensional Arrays by Custom Condition
Learn how to efficiently filter a PHP array of associative arrays based on a custom condition using `array_filter` and an anonymous function, ideal for data processing.
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30, 'active' => true],
['id' => 2, 'name' => 'Bob', 'age' => 24, 'active' => false],
['id' => 3, 'name' => 'Charlie', 'age' => 35, 'active' => true],
['id' => 4, 'name' => 'David', 'age' => 28, 'active' => false],
];
// Filter users who are active and older than 25
$filteredUsers = array_filter($users, function($user) {
return $user['active'] && $user['age'] > 25;
});
/*
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[age] => 30
[active] => 1
)
[2] => Array
(
[id] => 3
[name] => Charlie
[age] => 35
[active] => 1
)
)
*/
print_r($filteredUsers);
How it works: This snippet demonstrates how to filter an array of associative arrays using `array_filter`. It iterates through each element, applying a custom callback function. Only elements for which the callback returns `true` are included in the resulting array, allowing flexible filtering based on multiple criteria without modifying the original array.