PHP
Filter an Array Based on Custom Criteria
Learn how to efficiently filter elements from a PHP array using a user-defined callback function, keeping only items that meet specific conditions.
<?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' => false],
];
// Filter out inactive users who are also under 30
$activeAndMatureUsers = array_filter($users, function($user) {
return $user['active'] && $user['age'] >= 30;
});
print_r($activeAndMatureUsers);
// 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 using `array_filter()` to selectively include elements from an array based on a custom condition. The provided callback function receives each array element and should return `true` to keep the element or `false` to discard it. This is highly useful for refining datasets according to specific business logic without manual looping.