PHP
Filter PHP Array Elements Based on a Condition
Learn how to use array_filter in PHP to easily remove elements from an array that do not meet a specified condition using a callback function.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out even numbers
$oddNumbers = array_filter($numbers, function($number) {
return $number % 2 != 0;
});
print_r($oddNumbers);
$users = [
['id' => 1, 'name' => 'Alice', 'active' => true],
['id' => 2, 'name' => 'Bob', 'active' => false],
['id' => 3, 'name' => 'Charlie', 'active' => true],
];
// Filter active users
$activeUsers = array_filter($users, function($user) {
return $user['active'];
});
print_r($activeUsers);
?>
How it works: This snippet demonstrates `array_filter()` which iterates over each value in an array, passing it to the provided callback function. If the callback function returns `true`, the value is kept; otherwise, it is removed. This is highly efficient for selective data extraction based on custom logic, such as filtering a list of numbers or an array of user objects.