PHP

Filtering PHP Arrays with Custom Callbacks

Efficiently filter elements from a PHP array using a custom callback function, allowing precise selection based on specific criteria or conditions.

<?php
$users = [
    ['id' => 1, 'name' => 'Alice', 'age' => 30, 'active' => true],
    ['id' => 2, 'name' => 'Bob', 'age' => 25, 'active' => false],
    ['id' => 3, 'name' => 'Charlie', 'age' => 35, 'active' => true],
    ['id' => 4, 'name' => 'David', 'age' => 22, 'active' => true]
];

// Filter users who are active and older than 25
$activeAndOlderUsers = array_filter($users, function($user) {
    return $user['active'] && $user['age'] > 25;
});

print_r($activeAndOlderUsers);

// 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: This snippet demonstrates how to use `array_filter()` to selectively retrieve elements from an array based on custom logic. The second argument is a callback function that receives each element. If the callback returns `true`, the element is included in the new filtered array; otherwise, it's excluded. This is highly useful for querying data within arrays, such as a list of users or products.

Need help integrating this into your project?

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

Hire DigitalCodeLabs