0

Hi!

I want to convert numbers to letters, in this way: A=0, B=1, C=2... Z=25, AA=26,AB=27 etc
(something like the names of columns in MS Excel). How to do that? Thanks a lot!

3
Contributors
6
Replies
10
Views
6 Years
Discussion Span
Last Post by diafol
0

nice and easy :-)

$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');

$i = 5;
echo $alpha[$i]; //will output letter E

0
function getColNo($colLetters){
  $limit = 5; //apply max no. of characters
  $colLetters = strtoupper($colLetters); //change to uppercase for easy char to integer conversion
  $strlen = strlen($colLetters); //get length of col string
  if($strlen > $limit)return "Column too long!"; //may catch out multibyte chars in first pass
  preg_match("/^[A-Z]+$/",$colLetters,$matches); //check valid chars
  if(!$matches)return "Invalid characters!"; //should catch any remaining multibyte chars or empty string, numbers, symbols
  $it = 0; $vals = 0; //just start off the vars
  for($i=$strlen-1;$i>-1;$i--){ //countdown - add values from righthand side
	$vals += (ord($colLetters[$i]) - 64 ) * pow(26,$it); //cumulate letter value
	$it++; //simple counter
  }
  return $vals - 1; //this is the answer
}
//sample usage:
echo getColNo("BX");

The ord and -64 get the value of the letter (ASCII goes from A (65) to Z (90)). SO -64 will give A=1, B=2 etc. You need to multiply this value by the number base (26) to the exponent (0 = rightmost letter, 1= next letter to left... etc), so no change for rightmost letter. next letter to left will be multiplied by 26. Take off 1 at the end to start counting at A = 0.

Perhaps easier method out there?

Edited by diafol: n/a

0

I mean, to do this with words (something like this site:click)
For both: from letters to numbers and from numbers to letters.

0

I answered the question you posed I think. Now you want something else? Try the code and you'll that it works to at least 10 characters. I didn't cheat like the site and have Z=0 either!
If you want numbers to letters, I reckon you can backwards engineer my solution and do it yourself.
I shouldn't have posted the whole solution anyway, bit previous of me. Sorry folks.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.