How to filter an array by a condition

Viewed 91927

I have an array like this:

array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2)

Now I want to filter that array by some condition and only keep the elements where the value is equal to 2 and delete all elements where the value is NOT 2.

So my expected result array would be:

array("a" => 2, "c" => 2, "f" => 2)

Note: I want to keep the keys from the original array.

How can I do that with PHP? Any built-in functions?

9 Answers

This can be handled using a closure. The following answer is inspired by PHP The Right Way:

//This will create an anonymous function that will filter the items in the array by the value supplied
function cb_equal_to($val)
{
    return function($item) use ($val) {
        return $item == $val;
    };
}

$input = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);

// Use array_filter on a input with a selected filter function
$filtered_array = array_filter($input, cb_equal_to(2));

Contents of $filtered_array would now be

array ( ["a"] => 2 ["c"] => 2 ["f"] => 2 ) 

I think the snappiest, readable built-in function is: array_intersect()

Code: (Demo)

$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
var_export(array_intersect($array, [2]));

Output:

array (
  'a' => 2,
  'c' => 2,
  'f' => 2,
)

Just make sure you declare the 2nd parameter as an array because that is the value type expected.

Now there is nothing wrong with writing out a foreach loop, or using array_filter(), they just have a more verbose syntax.

array_intersect() is also very easy to extend (include additional "qualifying" values) by adding more values to the 2nd parameter array.


From PHP7.4, arrow function syntax is available. This affords more concise code and the ability to access global variables without use.

Code: (Demo)

$haystack = [
    "a" => 2,
    "b" => 4,
    "c" => 2,
    "d" => 5,
    "e" => 6,
    "f" => 2
];
$needle = 2;

var_export(
    array_filter(
        $haystack,
        fn($v) => $v === $needle
    )
);

You can do something like:

$array = array("a" => 2, "b" => 4, "c" => 2, "d" => 5, "e" => 6, "f" => 2);
$arrayFiltered = array_filter($array, function ($element) {
    return $element == 2;
});

or:

$arrayFiltered = array_filter($array, fn($element) => $element == 2);
Related