Sling Academy
Home/PHP/How to Filter an Array in PHP by a Condition

How to Filter an Array in PHP by a Condition

Last updated: January 10, 2024

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.

Next Article: 5 Ways to Merge Arrays in PHP (with Examples)

Previous Article: Working with Nested Arrays in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array