Reputation: 9579
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.
Upvotes: 2
Views: 7609
Reputation: 47854
With modern PHP, you can use arrow function syntax to access the second array without use()
. As you iterate all of the values in the first array, check the mapping/second array for a matching key. If a match is found, use that; otherwise use the null coalescing operator to fallback to the original value.
Code: (Demo)
var_export(
array_map(
fn($v) => $b[$v] ?? $v,
$a
)
);
With the asker's original arrays, all elements are mapped, so the null coalescing is not necessary -- this is just a way to cover similar questions with missing keys in the lookup array.
If the lookup array might contain null
values, then you'll need to use key_exists()
like this.
Upvotes: 1
Reputation: 1423
$c = array();
foreach ($a as $key => $value)
{
if (isset($b[$value]))
{
$c[] = $b[$value];
}
}
Upvotes: 2
Reputation: 9579
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 :-)
Upvotes: 1
Reputation: 16709
$c = array_merge(array_intersect_key(array_flip($a), $b), $b);
$c = array_values($c);
Not really a one-liner, but close :P
Upvotes: 2