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_convertfunctions when the base is below 36 for faster execution.
- The output number is backward compatible with the native
- Can be used to convert to and from arbitrary bases between 2-64.
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);
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