Get from the associative array only those elements that are specified

Late, and I know this is a very simple question, but right now I have no idea, and the deadline is near.

I have two arrays:

$array1 = array( 'a' => 'asdasd', 'b' => 'gtrgrtg', 'c' => 'fwefwefw', 'd' => 'trhrtgr', ); $array2 = array( 'b', 'c' ); 

What was the name of the function to get the part of the intermediary array by the keys from the second array?

 $result = array( 'b' => 'gtrgrtg', 'c' => 'fwefwefw', ); 

Thanks!

+6
arrays php
source share
3 answers

Try the following:

 array_intersect_key($array1, array_flip($array2)). 
+20
source share

I think there is no such function, so I will implement it:

 function array_filter_keys($array, $keys) { $newarray = array(); foreach ($keys as $key) { if (array_key_exists($key, $array)) $newarray[$key] = $array[$key]; } return $newarray; } 
0
source share

I am curious to see if there is a built-in function that does this. This is how I do it.

 $result = array(); foreach ($array2 as $key) { if (array_key_exists($key, $array1) { $result[$key] = $array1[$key]; } } 
0
source share

All Articles