0
$encoding = [0 => 'X', 1 => 'K', 2 => 'L', 3 => 'R', 4 => 'B'];

$digits = [1, 1, 4, 2];

// result should then equal ['K', 'K', 'B', 'L']

I can easily do this with a foreach loop and push into a new array.

$encoding = [0 => 'X', 1 => 'K', 2 => 'L', 3 => 'R', 4 => 'B'];
$digits = [1, 1, 4, 2];
$result = [];

foreach($digits as $digit) {
    $result[] = $encoding[$digit];
}

But I can't find if there is a function inbuilt into php to handle this OR a library of helper functions that can do this?

I also want it to be able to do the inverse and decode the value back to its digits.

2
  • Maybe array_intersect() ? Commented Feb 26, 2019 at 1:41
  • Couldn't get it to work because the keys have duplicates. Commented Feb 26, 2019 at 1:41

1 Answer 1

1

One possibility is to use array_map:

$encoded = array_map(function ($v) use ($encoding) { return $encoding[$v]; }, $value);

Output:

Array ( [0] => K [1] => K [2] => B [3] => L )

To decode the result, you can use array_map again, this time using array_search to find the appropriate key value to return:

$decoded = array_map(function ($v) use ($encoding) { return array_search($v, $encoding);}, $encoded);

Or as suggested by @Barmar which is probably more efficient:

$encoding_f = array_flip($encoding);
$decoded = array_map(function ($v) use ($encoding_f) { return $encoding_f[$v];}, $encoded);

Output:

Array ( [0] => 1 [1] => 1 [2] => 4 [3] => 2 )
Sign up to request clarification or add additional context in comments.

4 Comments

How would you also do the inverse of this to decode the value?
@robertmylne Use array_flip() to invert the encoding array.
Don't call array_flip in the callback function, do it once before mapping.
@Barmar done. I wanted to keep it a one-liner but that is clearly better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.