khizar123456
khizar123456

Reputation: 27

Convert Digit into Letter

I have digit string and convert into letters.

$arr = str_split('12345');
Array
 (
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 4
  [4] => 5
 )

Now I want to Convert 1 = A, 2 = B, ...

Upvotes: 0

Views: 72

Answers (3)

Aymen Badri
Aymen Badri

Reputation: 5

Try getting them from their ASCII Code like this :

<?php
$arr = str_split('12345');
$str = chr($arr[0]+64);
echo ("str=".$str."\n");
?>

Upvotes: 0

Loko
Loko

Reputation: 6679

By using base_convert, I made this:

$arr = str_split('12345');

foreach($arr as $something){
    if($something==1){
        $value=$something*10;
    }else{
        $value++;
    }
    echo base_convert($value, 10, 36);
}

Might not be the best solution but it is a solution. I'll explain what I did here.

In the docs it says:

Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35

So I just made sure 1=10,2=11,3=12,4=13,5=14 etc...

Result: abcde

Upvotes: 0

ksbg
ksbg

Reputation: 3294

Easiest solution I can think of right now:

$arr = str_split('12345');
$arr2 = str_split('abcdefghijklmnopqrstuvwxyz');

foreach($arr as &$digit)
    $digit = $arr2[$digit-1];

note that $digit is passed to the loop by reference using a & symbol. That means that when you manipulate $digit, the respective array entry in $arr will be changed as well.

Upvotes: 2

Related Questions