PHP

Filter PHP Array Elements by Custom Condition

Learn to efficiently filter elements from a PHP array using a callback function. This snippet shows how to remove unwanted items based on specific criteria.

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$evenNumbers = array_filter($numbers, function($number) {
    return $number % 2 === 0;
});

echo "Even Numbers: ";
print_r($evenNumbers);

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

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

echo "Active Users: ";
print_r($activeUsers);
?>
How it works: The `array_filter()` function iterates over each value in an array, passing it to a user-defined callback function. If the callback returns `true`, the value is kept in the new filtered array; otherwise, it's discarded. This allows for highly flexible filtering logic, perfect for selecting specific data subsets based on any desired condition.

Need help integrating this into your project?

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

Hire DigitalCodeLabs