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?
$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));
You can give a try to array_replace
The simplest/least verbose way I can think of:
return array_map(function($value) use ($replacements) {
return array_key_exists($value, $replacements) ? $replacements[$value] : $value;
}, $data);
Using array_map
is basically just looping over the array, which any other base function would also have to do anyway.