Reputation: 4835
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)
Upvotes: 82
Views: 106631
Reputation: 8480
I think you are searching for array_intersect_key. Example:
$arr = [ "key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400 ];
$keys = [ "key2", "key4" ];
print_r(
array_intersect_key(
$arr,
array_flip($keys)
)
);
Would return:
Array ( [key2] => 200 [key4] => 400 )
You may use ['key2' => '', 'key4' => ''
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.
Upvotes: 170
Reputation:
An alternative answer:
$keys = array("key2", "key4");
return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);
Upvotes: 29
Reputation: 527458
foreach($input_arr as $key) {
$output_arr[] = $mapping[$key];
}
This will result in $output_arr
having the values corresponding to a list of keys in $input_arr
, based on the key->value mapping in $mapping
. If you want, you could wrap it in a function:
function get_values_for_keys($mapping, $keys) {
foreach($keys as $key) {
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
Then you would just call it like so:
$a = array('a' => 1, 'b' => 2, 'c' => 3);
$values = get_values_for_keys($a, array('a', 'c'));
// $values is now array(1, 3)
Upvotes: 10