I was wondering, how it is possible to perform function on each array element based on value.
For example, if I have two arrays:
[
0 => 'gp',
1 => 'mnp',
2 => 'pl',
3 => 'reg'
]
And
$translation = [
'gp' => 'One',
'mnp' => 'Two',
'pl' => 'Three',
'reg' => 'Four',
'other' => 'Five',
'fs' => 'Six'
];
How can I get
[
0 => 'One',
1 => 'Two',
2 => 'Three',
3 => 'Four'
]
?
I managed with foreach, but I believe there are some more efficient ways to do that. I tried to play around with array_walk
and array_map
, but din't get it. :(
<?php
$arr = [
0 => 'gp',
1 => 'mnp',
2 => 'pl',
3 => 'reg'
];
$translation = [
'gp' => 'One',
'mnp' => 'Two',
'pl' => 'Three',
'reg' => 'Four',
'other' => 'Five',
'fs' => 'Six'
];
$output = array_map(function($value)use($translation){
return $translation[$value];
}, $arr);
print_r($output);
Output:
Array
(
[0] => One
[1] => Two
[2] => Three
[3] => Four
)