How to Filter an Array in PHP by a Condition

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Filtering an array in PHP by a condition is a common task that can be achieved with the array_filter() function. This tutorial demonstrates various ways to apply filters on arrays, refining elements based on custom conditions.

Using array_filter()

The array_filter() function passes each value of an input array to a given callback function. If the callback function returns true, the current value is included in the result array. Here’s a simple example:

$numbers = [1, 2, 3, 4, 5, 6];

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

print_r($even_numbers);
// Output: Array ( [1] => 2 [3] => 4 [5] => 6 )

Using Custom Callback Functions

For more complex conditions, you can define a custom callback function separately and pass its name to array_filter():

function is_even($number) {
    return $number % 2 == 0;
}

$numbers = [1, 2, 3, 4, 5, 6];
$even_numbers = array_filter($numbers, 'is_even');

print_r($even_numbers);
// Output: Array ( [1] => 2 [3] => 4 [5] => 6 )

Filtering with Array Keys

array_filter() can also consider array keys in the filtering process. By default, it doesn’t, but you can pass a flag to change this behavior:

$assoc_array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

function key_is_even($key) {
    $even_keys = ['b', 'd'];
    return in_array($key, $even_keys);
}

$filtered_array = array_filter($assoc_array, 'key_is_even', ARRAY_FILTER_USE_KEY);

print_r($filtered_array);
// Output: Array ( [b] => 2 [d] => 4 )

Filtering with Both Array Keys and Values

For filtering based on both keys and values, array_filter() supports a third flag:

function key_value_even($value, $key) {
    return ($key == 'b' || $key == 'd') && $value % 2 == 0;
}

$assoc_array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$filtered_array = array_filter($assoc_array, 'key_value_even', ARRAY_FILTER_USE_BOTH);

print_r($filtered_array);
// Output: Array ( [b] => 2 [d] => 4 )

Advanced Techniques for Array Filtering

For more advanced scenarios, array filtering can be combined with other functions like array_map() and array_reduce():

// Sample array of numbers
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter even numbers, square each, and sum the squared values
$result = array_reduce(
    array_map(
        fn($num) => $num * $num,
        array_filter(
            $numbers,
            fn($num) => $num % 2 === 0
        )
    ),
    fn($carry, $item) => $carry + $item,
    0
);

echo $result; // Output: 220

In this example, we filter the even numbers from the array, square each of them using array_map(), and finally sum the squared values using array_reduce(). This demonstrates the combination of array filtering with other array functions for advanced manipulation.

Conclusion

This guide has explored how to filter arrays in PHP using the array_filter() function with several levels of complexity. Learning how to effectively filter and process array data is a valuable skill for any PHP developer.