Adam Griffith
Adam Griffith

Reputation: 357

Merge two arrays keeping the first array values as keys and second array values as values

Basically i have an array of key mappings (actually translations) and an array of data values. I want to essentially replace the keys of the second array with the values of the first array.

E.G.:

$array1 = array(
  'key1' => 'newkey1',
  'key2' => 'newkey2',
  'key3' => 'newkey3',
  'key4' => 'newkey4'
);

$array2 = array(
  'key1' => 'data1',
  'key2' => 'data2',
  'key3' => 'data3',
  'key4' => 'data4',
  'key5' => 'data5',
  'key6' => 'data6'
);

$result = array(
  'newkey1' => 'data1',
  'newkey2' => 'data2',
  'newkey3' => 'data3',
  'newkey4' => 'data4'
);

Edit: Added excess data to second array

Upvotes: 0

Views: 103

Answers (1)

Amal Murali
Amal Murali

Reputation: 76646

If you're sure that the number of elements in both the arrays are same, you can simply use array_combine():

$result = array_combine($array1, $array2);

If your second array contains excess elements, then you could use array_intersect_key() to remove them before using array_combine():

$values = array_intersect_key($array1, $array2);
$result = array_combine($array1, $values);

Demo

Upvotes: 7

Related Questions