3

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.

1 Answer 1

3

You can use array_intersect_key() (https://www.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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why is ksort() a good idea? I assume you think it will optimize performance?
Well, just to play safe... so when array_combine() runs it will combine them in proper keys orders... Just to play safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.