Convert Number to String and String to Number

Posted on 2009-04-15
Last Modified: 2012-05-06
I have a number and want to convert to excel style letting
1 - A
2 - B
3 - C
27 - AA
And back to a number.

The below function seems to correctly encode a number to string, I can't figure out how to change back to a number after 'ZZ'.

Thanks in advance

    function __numtoalpha($v)  {

        $return = '';

        while( $v >= 1 ) {

            $v = $v - 1;

            $return = chr(($v % 26)+65).$return;

            $v = $v / 26;


        return $return;



Open in new window

Question by:nbcit
    LVL 20

    Expert Comment

    Even though Excel would continue with AAA, you mean you want to start with numbers after ZZ? I.e.
    A B C ... Z AA AB ... ZY ZZ 1 2 3 4 5 6 7 8 9 10 11 12 ... ?
    Or did I misunderstand and what you want is the inverse function __alphatonum() which mas e.g. "A" -> 1 ?

    Accepted Solution

          function __alphatonum($v) {
                $return = 0;
                $v = strrev(strtoupper($v));
                for ($i=0;$i<strlen($v);$i++) $return += max(1,pow(26,$i))*(ord($v[$i])-64);
                return $return;

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    These days socially coordinated efforts have turned into a critical requirement for enterprises.
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    6 Experts available now in Live!

    Get 1:1 Help Now