PHP: create an array of values ​​in two arrays based on matching keys

Problem

I would like to create a new associative array with the corresponding values ​​from two arrays in which the keys from each array correspond.

For instance:

// first (data) array:
["key1" => "value 1", "key2" => "value 2", "key3" => "value 3"];

// second (map) array:
["key1" => "map1", "key3" => "map3"];

// resulting (combined) array:
["map1" => "value 1", "map3" => "value 3"];

What i tried

$combined = array();
foreach ($data as $key => $value) {
    if (array_key_exists($key, $map)) {
        $combined[$map[$key]] = $value;
    }
}

Question

Is there a way to do this using native PHP functions? Ideally one that is no more confusing than the code above ...

This question is similar to Merging arrays based on keys from another array . But not for sure.

It is also not as simple as using array_merge()and / or array_combine(). Note that arrays are not necessarily the same in length.

+3
source share
1 answer

array_intersect_key() (http://ca2.php.net/manual/en/function.array-intersect-key.php). - :

$int = array_intersect_key($map, $data);
$combined = array_combine(array_values($map), array_values($int));

ksort() $map, $data.

+3

All Articles