PHP
Filter Array of Objects by Multiple Conditions in PHP
Filter a PHP array containing associative arrays (or objects) based on multiple conditions across different keys, effectively simulating a database 'WHERE' clause with custom logic.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30, 'active' => true],
['id' => 2, 'name' => 'Bob', 'age' => 24, 'active' => false],
['id' => 3, 'name' => 'Charlie', 'age' => 30, 'active' => true],
['id' => 4, 'name' => 'David', 'age' => 35, 'active' => false],
['id' => 5, 'name' => 'Eve', 'age' => 28, 'active' => true]
];
// Filter users who are active AND younger than 30
$filteredUsers = array_filter($users, function($user) {
return $user['active'] === true && $user['age'] < 30;
});
echo "Active users younger than 30:
";
print_r(array_values($filteredUsers)); // array_values() re-indexes the array
// Filter users who are inactive OR exactly 30 years old
$anotherFilteredUsers = array_filter($users, function($user) {
return $user['active'] === false || $user['age'] === 30;
});
echo "
Inactive or 30-year-old users:
";
print_r(array_values($anotherFilteredUsers));
?>
How it works: This snippet demonstrates how to filter an array of associative arrays (or objects) based on multiple conditions using `array_filter()`. The function takes the array and a callback. The callback receives each element of the array and should return `true` if the element should be included in the filtered result, or `false` otherwise. By combining multiple logical conditions (`&&` for AND, `||` for OR) within the callback, you can create powerful and specific filters. `array_values()` is used afterward to reset the array keys, as `array_filter()` preserves the original keys, which can lead to sparse arrays.