PHP

Filter an Array of Associative Arrays by Custom Condition

Efficiently filter a PHP array containing associative arrays based on dynamic, multiple conditions using a custom callback function for precise data selection.

$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' => true]
];

// Filter for active users older than 25
$filteredUsers = array_filter($users, function($user) {
    return $user['active'] === true && $user['age'] > 25;
});

print_r($filteredUsers);
/*
Expected output:
Array
(
    [0] => Array ( [id] => 1 [name] => Alice [age] => 30 [active] => 1 )
    [2] => Array ( [id] => 3 [name] => Charlie [age] => 35 [active] => 1 )
    [3] => Array ( [id] => 4 [name] => David [age] => 28 [active] => 1 )
)
*/
How it works: This code demonstrates how to use `array_filter` with an anonymous function to filter an array of associative arrays based on multiple, custom conditions. The callback function receives each inner associative array as an argument and should return `true` if the item should be included in the filtered result, or `false` otherwise. This provides a flexible way to select specific records based on criteria that might involve several fields or complex logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs