In PHP, is there a way to get a subset of an array whose keys match the values ​​in another array?

I am currently using this get indicies function to collect key / values ​​from an array for an array of keys stored as values ​​in another array:

 function get_indicies($haystack,$needle_names = array()){ $needles = array(); foreach($needle_names as $needle_name){ if( isset($haystack[$needle_name]) ) $needles[$needle_name] = $haystack[$needle_name]; } return $needles; } 

There is a ton of array functions in php, is there a way that I can do this more efficiently in a sphere class, and the user has more php built-in functions?

+4
source share
1 answer
 $subset = array_intersect_key($haystack, array_flip($needleNames)); 

This is often used under the name pluck or similarly as a helper function.

 function pluck(array $array, $keys) { if (!is_array($keys)) { $keys = func_get_args(); array_shift($keys); } return array_intersect_key($array, array_flip($keys)); } var_dump(pluck($array, array('foo', 'bar', 'baz'))); var_dump(pluck($array, 'foo', 'bar', 'baz')); 
+4
source

All Articles