Search code examples
phparraysmapping

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?


Solution

  • <?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.