PHP [Array Keys] : Convert “0” Into “A”, “1” Into “B”… (and so “89” will be “IJ”) Function

StackOverflow https://stackoverflow.com/questions/10022481

  •  29-05-2021
  •  | 
  •  

Question

Let's say I have an array like this:

$array = array
("this","is","me","and","I","am","an","array","hello","beautiful","world");

How can I create a function that converts 0 into "A", 1 into "B"...? Using Foreach or...?

So that instead of

 Array
(
    [0] => this
    [1] => is
    [2] => me
    [3] => and
    [4] => I
    [5] => am
    [6] => an
    [7] => array
    [8] => hello
    [9] => beautiful
    [10] => world
)

I would get

 Array
(
    ['A'] => this
    ['B'] => is
    ['C'] => me
    ['D'] => and
    ['E'] => I
    ['F'] => am
    ['G'] => an
    ['H'] => array
    ['I'] => hello
    ['J'] => beautiful
    ['BA'] => world
)
Was it helpful?

Solution

function digits_to_letters($input) {
    return strtr($input, "0123456789", "ABCDEFGHIJ");
}

$result = array_flip(array_map("digits_to_letters", array_flip($original)));

(Example run: http://ideone.com/TQNYj)


If you preferred a foreach over array_flip+array_map, you could use this instead:

$result = array();
foreach($original as $k => $v) {
    $result[strtr($k, "0123456789", "ABCDEFGHIJ")] = $v;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top