shi jack
shi jack

Reputation: 37

Replace an array's values with the values from a lookup array

I have two arrays. The one's array key is another's value. Here is code:

$arr1 = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'pear',
);

$arr2 = array(
    'bird' => 'a',
    'dog' => 'b',
);

And my question, how to combine two arrays in one like:

$arr3 = array(
    'bird' => 'apple',
    'dog' => 'banana',
);

Is there have some array function to do this probably?

Upvotes: 1

Views: 77

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79024

Edit: This is a fun way and matches the keys:

$arr3 = array_combine(array_intersect_key($k = array_flip($arr2), $arr1),
                      array_intersect_key($arr1, $k));

Original with no key matching:

Here's a way. Doesn't matter which array is longer:

$arr3 = array_combine(array_slice(array_keys($arr2), 0, count($arr1)),
                      array_slice($arr1, 0, count($arr2)));

Upvotes: 1

Mark Eriksson
Mark Eriksson

Reputation: 1475

<?php
$arr3 = array();

foreach ($arr2 as $item => $value) {
  $arr3[$item] = $arr1[$value];
}
print_r($arr3);

something along those lines anyway.

If you literally want to merge the arrays, array_merge will do the job fine.

Upvotes: 1

Related Questions