Search code examples
phparraysreplacemappinglookup

Replace values in a flat array using an associative, lookup/mapping array


This should be an easy one liner, but I can't quite get it:

I have an array like this:

$a = ["z", "x", "y"];

and an array like this:

$b = ["x"=>"a", "y"=>"b", "z"=>"c"];

what is a php oneliner to get:

$c = ["c", "a", "b"];

I want to use each element of a to index into b and return an array of the results I've been looking at array_map but couldn't figure out how to bind b to the callback function.


Solution

  • Here is the solution I ended up with with help from @onetrickpony:

    $a = array("z", "x", "y");
    $b = array("x"=>"a", "y"=>"b", "z"=>"c");
    
    $c = array_map(function($key) use ($b){ return $b[$key]; }, $a);
    

    The key to this is the 'use' keyword to bind to the associative array to the closure. Pretty simple once you know what you are looking for :-)