PHP

Filter an Array by Custom Condition

Efficiently filter PHP arrays using a callback function to remove elements that do not meet specified criteria, creating a new filtered array.

<?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'] === true;
});

print_r($activeUsers);

?>
How it works: The `array_filter()` function iterates over an array, passing each value to a user-defined callback function. If the callback function returns `true`, the value from the input array is included in the new filtered array; otherwise, it's excluded. This snippet demonstrates filtering both a simple numeric array and an array of associative arrays based on different conditions, providing a powerful way to select specific elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs