Get array values by keys
I am searching for a built in php function that takes array of keys as input and returns me corresponding values.
for e.g. I have a following array
$arr = array("key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400);
and I need values for the keys key2 and key4 so I have another array("key2", "key4")
I need a function that takes this array and first array as inputs and provide me values in response. So response will be array(200, 400)
Solution 1:
I think you are searching for array_intersect_key. Example:
array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5),
array_flip(array('a', 'c')));
Would return:
array('a' => 1, 'c' => 5);
You may use array('a' => '', 'c' => '')
instead of array_flip(...)
if you want to have a little simpler code.
Note the array keys are preserved. You should use array_values afterwards if you need a sequential array.
Solution 2:
An alternative answer:
$keys = array("key2", "key4");
return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);