PHP
Filter Array by Multiple Conditions
Learn to filter a PHP array of associative arrays or objects using multiple dynamic conditions with `array_filter` and an anonymous function, perfect for advanced data selection.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30, 'status' => 'active'],
['id' => 2, 'name' => 'Bob', 'age' => 25, 'status' => 'inactive'],
['id' => 3, 'name' => 'Charlie', 'age' => 35, 'status' => 'active'],
['id' => 4, 'name' => 'David', 'age' => 25, 'status' => 'active'],
['id' => 5, 'name' => 'Eve', 'age' => 40, 'status' => 'pending'],
];
// Filter for active users older than 28
$filteredUsers = array_filter($users, function($user) {
return $user['status'] === 'active' && $user['age'] > 28;
});
print_r($filteredUsers);
/*
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
[age] => 30
[status] => active
)
[2] => Array
(
[id] => 3
[name] => Charlie
[age] => 35
[status] => active
)
)
*/
// Filter for users with 'Bob' or 'Eve' name AND age less than 40
$specificUsers = array_filter($users, function($user) {
return (in_array($user['name'], ['Bob', 'Eve'])) && $user['age'] < 40;
});
print_r($specificUsers);
/*
Output:
Array
(
[1] => Array
(
[id] => 2
[name] => Bob
[age] => 25
[status] => inactive
)
)
*/
How it works: This snippet illustrates how to effectively filter an array containing associative arrays (or objects) based on multiple conditions. It uses the `array_filter` function with an anonymous callback function that returns `true` for elements that should be included in the filtered result, allowing for complex logical conditions.