PHP

Filtering an Array by Custom Conditions

Efficiently filter PHP arrays based on specific criteria using `array_filter` and a callback function to extract relevant elements.

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

// Filter active users older than 25
$activeUsersOlderThan25 = array_filter($users, function($user) {
    return $user['active'] && $user['age'] > 25;
});

print_r($activeUsersOlderThan25);

// Example with a simple indexed array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenNumbers = array_filter($numbers, function($num) {
    return $num % 2 === 0;
});

print_r($evenNumbers);
?>
How it works: This snippet demonstrates how to use `array_filter()` to create a new array containing only elements that satisfy a specified condition. It takes an array and a callback function as arguments. The callback function is executed for each element, and if it returns `true`, the element is included in the filtered array. This is extremely useful for refining data based on various criteria.

Need help integrating this into your project?

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

Hire DigitalCodeLabs