0

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

1 Answer 1

7

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

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

2 Comments

Thanks very much for the quick reply. However as vee states what happens if the second array has some unwanted key/values?
@adamjg: Can you post an example array in eval.in ? I'm not sure what you mean.

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.