Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to output list like this: AA, AB, AC, all the way to ZZZY, ZZZZ, ZZZZA etc

I'm trying to write a function that'll convert an integer to a string like this, but I can't figure out the logic... :(

1 = a
5 = e
27 = aa
28 = ab
etc...

Can anyone help? I'm really niffed that I can't wrap my head around how to write this... :(

like image 218
i-CONICA Avatar asked Apr 05 '11 15:04

i-CONICA


2 Answers

Long list of them here:

/*
 * Convert an integer to a string of uppercase letters (A-Z, AA-ZZ, AAA-ZZZ, etc.)
 */
function num2alpha($n)
{
    for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
        $r = chr($n%26 + 0x41) . $r;
    return $r;
}

/*
 * Convert a string of uppercase letters to an integer.
 */
function alpha2num($a)
{
    $l = strlen($a);
    $n = 0;
    for($i = 0; $i < $l; $i++)
        $n = $n*26 + ord($a[$i]) - 0x40;
    return $n-1;
}
like image 62
Kelly Avatar answered Nov 19 '22 14:11

Kelly


I'll add this answer to sum up the comments regarding the misuse of base-26.

A common first reaction when confronted with this problem is to think "There are 26 letters, so this must be base-26! All I need to do is map each letter to its corresponding number".

But this is not base-26. It's easy to see why: there is no zero!

In base-26, the number twenty-six is the first number with two digits, and is written "10". In this counting system, twenty-six has a single digit, "Z", and the first two-digit number is twenty-seven.

But what if we make A=0, ..., Z=25? This way we have a zero and the first two-digit number becomes twenty-six. So far so good. How do we write twenty-six now? That's "AA". But... isn't A=0? Ooops! A = AA = AAA = "0" = "00" = "000".

like image 7
R. Martinho Fernandes Avatar answered Nov 19 '22 14:11

R. Martinho Fernandes