| : | Javascript | : | PHP Index | : | MySQL | : |
| : | Source | : | : | Explanation | : | : | Example | : | : | Todo | : | : | Feedback | : |
Convert a decimal to an alphabetical (alphabet based) string
Added: 2006-05-05 18:41:23
Last update: 2007-09-30 17:20:32
<?
/******
* You may use and/or modify this script as long as you:
* 1. Keep my name & webpage mentioned
* 2. Don't use it for commercial purposes
*
* If you want to use this script without complying to the rules above, please contact me first at: marty@excudo.net
*
* Author: Martijn Korse
* Website: http://devshed.excudo.net
*
* Date: 2006-05-05 18:41:23
***/
/*****
* Converts any integer ($int) into an alphabetic range of $length length
* p.a.: 1 => AA, 2 => AB, 27 => BA
***/
function convDec2Alpha($int, $length=2)
{
$int = $int - 1; // minus one, cuz A is in position 0 in the alphabet array
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // the alphabet
$a = strlen($alphabet); // the length of the alphabet
$maxPosibilities = pow($a, $length); // maximum posibilities, given the the ($)length of the output and the length of the alphabet
$restValue = $int % $maxPosibilities; // if $int exceeds the maxPosibilities, we start counting again from scrats. For this, we use the modulus
$output = ""; // initiating output variable
$x = $length - 1;
/***
* We're gonna loop $length times, but since we end at 0 we start at $length -1.
* This is done on purpose, because x is gonna be used as a 'power of'
*/
while ($x >= 0)
{
// calculating the position (index) of the new character)
$thisCharIndex = floor($restValue / pow($a, $x));
$thisChar = $alphabet{$thisCharIndex};
$restValue = $restValue - (pow($a, $x) * $thisCharIndex);
// adding character to the output
$output .= $thisChar;
$x--;
}
return $output; // return output
}
/*****
* Converts any alphabetic range of characters into an integer ($int) value
* p.a.: AA => 1, AC => 3, BA => 27
***/
function convAlpha2Dec($str)
{
$str = strtoupper($str);
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // the alphabet
$maxI = (strlen($str) - 1);
$int = 0;
for ($i=0; $i<=$maxI; $i++)
{
$thisPos = strpos($alphabet, $str{$i});
if ($i < $maxI)
{
$int += pow(strlen($alphabet), ($maxI - $i)) * $thisPos;
}
else /* $i == $maxI */
{
$int += ($thisPos + 1);
}
}
return $int;
}?>