Newb
Newb

Reputation: 678

How to convert number to a letter in PHP?

How is this function numtoalpha to print out the alphabetic equivalents of values that will be greater than 9 used? Results, something like this: 10 for A, 11 for B, etc....

PHP.net does not even have that function or i did not look in the correct place, but I am sure it said functions.

<?php
$number = $_REQUEST["number"];
/*Create a condition that is true here to get us started*/
if ($number <=9)
{
echo $number;
}
elseif ($number >9 && $number <=35) 
{
echo $number;
function numtoalpha($number)
{
echo $number;
}
echo"<br/>Print all the numbers from 10 to 35, with alphabetic equivalents:A for10,etc";
?>

Upvotes: 2

Views: 14152

Answers (4)

Girish Sasidharan
Girish Sasidharan

Reputation: 588

Use following function.

function patient_char($str)
{
$alpha = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
$newName = '';
do {
    $str--;
    $limit = floor($str / 26);
    $reminder = $str % 26;
    $newName = $alpha[$reminder].$newName;
    $str=$limit;
} while ($str >0);
return $newName;
}

Upvotes: 0

dnagirl
dnagirl

Reputation: 20456

You're essentially going to do some math to generate the correct ascii code for the value you want.

So:

if($num>9 && $num<=35) {
 echo(chr(55+$num))
}

Upvotes: 6

ty812
ty812

Reputation: 3323

Try this:

<?php

  $number = $_REQUEST["number"];

  for ($i=0;$i<length($number);$i++) {
    echo ord($number[$i]);
  }

?>

This will give you the ascii code for the respective character. Diminish it by 55, and you get 10 for A, 11 for B etc ...

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319581

you need to use base_convert:

$number = $_REQUEST["number"];   # '10'
base_convert($number, 10, 36);   # 'a'

Upvotes: 10

Related Questions