PHP

Filtering an Array of Objects by Property Value

Learn how to efficiently filter a PHP array of objects or associative arrays based on a specific property's value using `array_filter` and an anonymous function.

$users = [
    ['id' => 1, 'name' => 'Alice', 'status' => 'active'],
    ['id' => 2, 'name' => 'Bob', 'status' => 'inactive'],
    ['id' => 3, 'name' => 'Charlie', 'status' => 'active'],
];

$activeUsers = array_filter($users, function($user) {
    return $user['status'] === 'active';
});

// To filter by an object property:
// class User { public $id; public $name; public $status; }
// $users = [new User(1, 'Alice', 'active'), ...];
// $activeUsers = array_filter($users, function($user) {
//     return $user->status === 'active';
// });

print_r($activeUsers);
How it works: `array_filter` iterates over each element in the `$users` array. The anonymous function is called for each element, and if it returns `true`, the element is included in the new `$activeUsers` array. This technique is ideal for selectively extracting data based on specific criteria from a collection of associative arrays or objects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs