Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The Problem

I would like to create a new associative array with respective values from two arrays where the keys from each array match.

For example:

// 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've Tried

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

The Question

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

This question is similar to Combining arrays based on keys from another array. But not exact.

It's also not as simple as using array_merge() and/or array_combine(). Note the arrays are not necessarily equally in length.

share|improve this question
add comment

1 Answer

You can use array_intersect_key() (http://ca2.php.net/manual/en/function.array-intersect-key.php). Something like that:

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

Also it would be a good idea ksort() both $map and $data.

share|improve this answer
    
Why is ksort() a good idea? I assume you think it will optimize performance? –  Jason McCreary Feb 12 at 20:09
    
Well, just to play safe... so when array_combine() runs it will combine them in proper keys orders... Just to play safe. –  cyadvert Feb 12 at 20:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.