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);