← Back to all snippets
PHP

Filter an Array of Associative Arrays by Multiple Conditions

Discover how to filter a PHP array of objects or associative arrays using array_filter with a custom callback for complex, multi-criteria searches and data subsetting.

$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'active' => true],
    ['id' => 2, 'name' => 'Bob', 'role' => 'editor', 'active' => false],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin', 'active' => false],
    ['id' => 4, 'name' => 'David', 'role' => 'user', 'active' => true],
    ['id' => 5, 'name' => 'Eve', 'role' => 'editor', 'active' => true]
];

// Filter for active admins
$activeAdmins = array_filter($users, function($user) {
    return $user['active'] === true && $user['role'] === 'admin';
});

// $activeAdmins will be:
// [
//     ['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'active' => true]
// ]

// Filter for users who are either 'editor' or 'admin' AND active
$activeEditorsOrAdmins = array_filter($users, function($user) {
    return $user['active'] === true && in_array($user['role'], ['editor', 'admin']);
});
How it works: This code demonstrates filtering an array of associative arrays based on multiple conditions using `array_filter()`. The anonymous callback function receives each array element and returns `true` if the element should be included in the filtered result, `false` otherwise. This allows for complex logic, combining different key values and even using other functions like `in_array()` for more advanced filtering.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs