Base62 Encoder for Short IDs
PHP Code Editor
Execution Result
Ready to execute
Click the "Run Script" button to see the output here
Description
When you want to expose a numeric id in a URL without it looking like a sequential integer or being needlessly long, base62 is the sweet spot. It uses only digits and letters, so it is URL-safe with no percent-encoding, and it is far denser than decimal: a 64-bit id fits in eleven characters instead of nineteen or so. This is the encoding behind most short-link services.
Encoding is the standard base conversion: repeatedly take the remainder modulo 62 to pick a character from the alphabet, prepend it, and integer-divide until the number is gone. Decoding reverses it by walking the string and accumulating position times 62 to the appropriate power. The alphabet ordering is what defines the scheme, keep encode and decode using the exact same string.
const BASE62 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function base62Encode(int $num): string {
if ($num < 0) {
throw new InvalidArgumentException('Non-negative integers only');
}
if ($num === 0) {
return '0';
}
$out = '';
while ($num > 0) {
$out = BASE62[$num % 62] . $out;
$num = intdiv($num, 62);
}
return $out;
}
function base62Decode(string $str): int {
$num = 0;
foreach (str_split($str) as $ch) {
$pos = strpos(BASE62, $ch);
if ($pos === false) {
throw new InvalidArgumentException("Invalid character: $ch");
}
$num = $num * 62 + $pos;
}
return $num;
}
echo base62Encode(125) . "\n"; // 21
echo base62Encode(1000000) . "\n"; // 4c92
echo base62Decode(base62Encode(987654321)) . "\n"; // 987654321
Comments
No comments yet
Be the first to share your thoughts!