really irked me. In conjunction with
thread, it seemed people were fine with a loop that constantly queried a database to see if a value already existed until they found one that didn't.
and I set about tonight finding a way to solve this.
record insertion (always unique) to generate this unique value (al la Short URL services).
For completeness, here is class.
PHP Code:
<?php
/**
* @author Anthony Sterling
*/
class Base62
{
/**
* @desc Holds the key used to encode and decode.
*
* @var Array
*/
protected static $aCharMap = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9'
);
/**
* @desc Encodes an integer to Base 62
*
* @param Integer $iInteger
* @return String
*/
public static function Encode($iInteger)
{
$sString = '';
while($iInteger > 0)
{
$sString .= (string)self::$aCharMap[$iInteger % 62];
$iInteger = floor($iInteger / 62);
}
return $sString;
}
/**
* @desc Decodes a Base 62 encoded string
*
* @param String $sString
* @return Integer
*/
public static function Decode($sString)
{
$aFlippedMap = array_flip(
self::$aCharMap
);
$iInteger = 0;
for($iCurrentPosition = 0; $iCurrentPosition < strlen($sString); $iCurrentPosition++)
{
$iInteger += $aFlippedMap[$sString[$iCurrentPosition]] * pow(62, $iCurrentPosition);
}
return $iInteger;
}
}
$iInteger = 2147483647;
$sEncoded = Base62::Encode($iInteger);
$iDecoded = Base62::Decode($sEncoded);
header('Content-Type: text/plain');
printf(
"
Attempting to Encode:\t%d
Encoded Value:\t\t%s
Decoded Value:\t\t%s
",
$iInteger,
$sEncoded,
$iDecoded
);
/*
Attempting to Encode: 2147483647
Encoded Value: bLMuvc
Decoded Value: 2147483647
*/
?>
Bookmarks