phpalgorithmbase62

Please explain this base 62 PHP conversion function/algorithm


Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.


Solution

  • You're over-complicating:

    private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    private static function _convertBase($num)
    {
        $base = strlen(self::$_characters); // 62
        $string = self::$_characters[$num % $base];
    
        while (($num = intval($num / $base)) > 0)
        {
            $string = self::$_characters[$num % $base] . $string;
        }
    
        return $string;
    }