user5564
user5564

Reputation:

Combine an array of keys and an array of values into a new array of key-value pairs

I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.

Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines?

$mapped_array = mapkeys($array_with_keys, $array_with_values);

Upvotes: 32

Views: 65813

Answers (3)

aib
aib

Reputation: 47011

See array_combine() on PHP.net.

Upvotes: 74

Christopher Lightfoot
Christopher Lightfoot

Reputation: 1167

(from the docs for easy reading)

array_combine — Creates an array by using one array for keys and another for its values

Description

array array_combine ( array $keys , array $values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Parameters

keys - Array of keys to be used. Illegal values for key will be converted to string.

values - Array of values to be used

Example

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

The above example will output:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

Upvotes: 18

Mathias
Mathias

Reputation: 51

This should do the trick

function array_merge_keys($ray1, $ray2) {
    $keys = array_merge(array_keys($ray1), array_keys($ray2));
    $vals = array_merge($ray1, $ray2);
    return array_combine($keys, $vals);
}

Upvotes: 5

Related Questions