PHP

Filter Associative Arrays by Multiple Conditions

Efficiently filter a list of associative arrays in PHP by applying multiple custom conditions using `array_filter` with a callback function for precise data selection.

<?php
$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 users who are active AND 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 )
)
*/

// Filter users named 'Alice' OR 'Charlie'
$specificUsers = array_filter($users, function ($user) {
    return in_array($user['name'], ['Alice', 'Charlie']);
});

print_r($specificUsers);

/* Expected Output:
Array
(
    [0] => Array ( [id] => 1 [name] => Alice [age] => 30 [active] => 1 )
    [2] => Array ( [id] => 3 [name] => Charlie [age] => 35 [active] => 1 )
)
*/
?>
How it works: The `array_filter()` function is used here to select elements from an array that pass a custom filtering condition defined in a callback function. By combining multiple conditions with logical operators (`&&` for AND, `||` for OR) within the callback, you can perform sophisticated filtering on associative arrays, retrieving precisely the data you need from a larger dataset while maintaining readability.

Need help integrating this into your project?

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

Hire DigitalCodeLabs