Get array values by keys

PhpArrays

Php Problem Overview


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)

Php Solutions


Solution 1 - Php

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 - Php

An alternative answer:

$keys = array("key2", "key4");

return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);

Solution 3 - Php

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyaz AlaviView Question on Stackoverflow
Solution 1 - PhpAndrewView Answer on Stackoverflow
Solution 2 - Phpuser2027151View Answer on Stackoverflow
Solution 3 - PhpAmberView Answer on Stackoverflow