← Back to all snippets
PHP

Filter Array Elements by a Custom Condition

Learn to filter PHP array elements based on any custom condition using array_filter(). Efficiently select specific data from your arrays with a callback function.

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

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

$users = [
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 25],
    ['name' => 'Charlie', 'age' => 35],
];

// Filter users older than 30
$olderUsers = array_filter($users, function($user) {
    return $user['age'] > 30;
});

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

echo "Users Older Than 30:
";
print_r($olderUsers);

// Note: array_filter preserves keys by default. To re-index numerically, use array_values().
$reindexedEvenNumbers = array_values($evenNumbers);
echo "Re-indexed Even Numbers:
";
print_r($reindexedEvenNumbers);
?>
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 current element is included in the result array; otherwise, it's excluded. This allows for highly flexible filtering based on any custom logic. By default, array_filter preserves the original keys, but array_values() can be used afterward to re-index the resulting array numerically if sequential integer keys are desired.

Need help integrating this into your project?

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

Hire DigitalCodeLabs