• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2457
  • Last Modified:

Convert Number to String and String to Number

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
<?php
    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

0
nbcit
Asked:
nbcit
1 Solution
 
thehagmanCommented:
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 ?
0
 
nbcitAuthor Commented:
<?php
      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;
      }
?>
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now