I am having one (associative) data array $data with values, and another associative array $replacements.
I am looking for a short, easy and fast way to replace values in $data using the $replacements array.
The verbose way would be this:
function replace_array_values(array $data, array $replacements) {
$result = [];
foreach ($data as $k => $value) {
if (array_key_exists($value, $replacements)) {
$value = $replacements[$value];
}
$result[$k] = $value;
}
return $result;
}
Is there a native way to do this?
I know array_map(), but maybe there is something faster, without an extra function call per item?
Example:
$data = array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
'd' => 'D',
);
$replacements = array(
'B' => '(B)',
'D' => '(D)',
);
$expected_result = array(
'a' => 'A',
'b' => '(B)',
'c' => 'C',
'd' => '(D)',
);
assert($expected_result === replace_array_values($data, $replacements));
$data,$replacementsand expected output?