Solved

Convert Number to String and String to Number

Posted on 2009-04-15
2,447 Views
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'.

``````<?php

function __numtoalpha(\$v)  {

\$return = '';

while( \$v >= 1 ) {

\$v = \$v - 1;

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

\$v = \$v / 26;

}

return \$return;

}

?>
``````
0
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 ?
0

Accepted Solution

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

Suggested Solutions

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), 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.