Base62: Convert a number to base 62 for short URLs in PHP

Base62 is a PHP class to convert a number to and from any base between 2-62.

There is no native function in PHP to convert upto base 62. The native function base_convert converts numbers upto base 36, ie. using 0-9 and a-z. Since URLs are case sensitive, we can use additional character set of A-Z to make a number even shorter.

Most of the examples I found on the internet were converting a decimal to 62 and most of them were using BC Math functions to achieve that functionality. This script removes those restrictions and you can use it to convert to and from arbitrary bases between 2-64.

Features and Optimizations

  • It doesn’t use BC Math functions so works without the use of BC Math library.
  • It uses the native base_convert functions when the base is below 36 for faster execution.
  • The output number is backward compatible with the native base_convert function.
  • Can be used to convert to and from arbitrary bases between 2-64.

Usage

The usage is pretty simple. You have to include the class file in your code and call the following function.

$converted_num= Base62::convert($number, $from_base, $to_base);

Example

echo Base62::convert(696952941);
// 'Lalit'
echo Base62::convert('Lalit', 62, 10);
// 696952941

Download (v0.1, 08 Dec, 2011)

The code is released under Apache License 2.0

Plaint text PHP source (v0.1) | Formatted PHP source (v0.1)

• • •

3 Responses to Base62: Convert a number to base 62 for short URLs in PHP

  1. fmod() is better than % for big int.

  2. Roman says:

    Arnaud!
    Thank you very much for Base62!!!

  3. Roman says:

    ahh sorry
    Lalit Patel, thank you ))