Skip to content

Instantly share code, notes, and snippets.

@Grebenschikov
Created September 23, 2016 08:52
Show Gist options
  • Save Grebenschikov/2807fc365763d9f3431d5baa3e8c5174 to your computer and use it in GitHub Desktop.
Save Grebenschikov/2807fc365763d9f3431d5baa3e8c5174 to your computer and use it in GitHub Desktop.
Convert int to arbitrary base with custom alphabet
<?php
echo base_encode('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 100500) . PHP_EOL;
function base_encode($alphabet, $number, $suffix = '') {
$base = strlen($alphabet);
if ($number >= $base) {
$div = intval($number / $base); // For php7: intdiv($number, $base);
$mod = $number % $base;
return base_encode($alphabet, $div, $alphabet[$mod] . $suffix);
} else {
return $alphabet[$number] . $suffix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment