Quantcast
Channel: User Ja͢ck - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by Ja͢ck for Filter a flat, associative array by the keys in another flat, associative array

$
0
0

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

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>