0

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:

See https://3v4l.org/g0sIJ

$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));
1
  • Can you show an example of $data, $replacements and expected output? Commented Mar 19, 2018 at 0:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

array_map() calls a function for each iteration, which adds some overhead (would be curious how much). It is still a correct answer though.
@donquixote I doubt this would be significant at all, but I may be wrong. Maybe you can run some benchmarks.
If you have a data-crunching algorithm where this is called a lot, then I bet it will be significant.
Or if the array is really big.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.