Snippet. PHP. Shortening Numbers

This PHP snippet allows the shortening of a number to shortened version, which will occupy less space. An example usage of this is an URL shortening service, where each URL is assigned an unique ID, which is consecutively shortened to produce the final short URL. The snippet contains also the unshortening version, which will restore original number.

function number_shorten($number){
    $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($codeset);
    $converted = "";
    
    while ($number > 0) {
        $converted = substr($codeset, ($number % $base), 1) . $converted;
        $number = floor($number/$base);
    }
    
    return $converted;
}
function number_unshorten($shortened){
    $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($codeset);
    $c = 0;
    for ($i = strlen($shortened); $i; $i--) {
        $c += strpos($codeset, substr($shortened, (-1 * ( $i - strlen($shortened) )),1)) * pow($base,$i-1);
    }
    return $c;
}

Example

$short = number_shorten(123456789);
echo $short;  // 8m0Kx

echo '
'; $number = number_unshorten($short); echo $number; // 123456789

Updated on: 26 Apr 2024