'array_filter based on keys from another array

I have two arrays:

$arr1 = array('a' => 10, 'b' => 20);

$arr2 = array('a' => 10, 'b' => 20, 'c' => 30);

How can I use array_filter to drop elements from $arr2 that don't exist in $arr1 ? Like "c" in my example...



Solution 1:[1]

Use in_array in your array_filter callback:

$arr2 = array_filter($arr2, function($e) use ($arr1) {
    return in_array($e, $arr1);
  });

Note that this will regard the values of the elements, not the keys. array_filter will not give you any key to work with so if that is what you need a regular foreach loop may be better suited.

Solution 2:[2]

To get the elements that exist in $arr2 which also exist in $arr1 (i.e. drop elements of $arr2 that don't exist in $arr1), you can intersect based on the key like this:

array_intersect_key($arr2, $arr1); // [a] => 10, [b] => 20

Update

Since PHP 7 it's possible to pass mode to array_filter() to indicate what value should be passed in the provided callback function:

array_filter($arr2, function($key) use ($arr1) {
  return isset($arr1[$key]);
}, ARRAY_FILTER_USE_KEY);

Since PHP 7.4 you can also drop the use () syntax by using arrow functions:

array_filter($arr2, fn($key) => isset($arr1[$key]), ARRAY_FILTER_USE_KEY);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emil Vikström
Solution 2