Skip to content

Instantly share code, notes, and snippets.

@rduarte
Created April 2, 2009 22:34
Show Gist options
  • Save rduarte/89540 to your computer and use it in GitHub Desktop.
Save rduarte/89540 to your computer and use it in GitHub Desktop.
base62 algorithm - encode and decode
<?php
function base62_encode($num){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = 62;
$result = '';
while($num >= $base) {
$r = $num%$base;
$result = $chars[$r].$result;
$num = $num/$base;
}
return $chars[$num].$result;
}
function base62_decode($id){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = 62;
for ($i=0; $i<strlen($id); $i++) {
$value = strpos($chars, $id[$i]);
$num = $value * pow($base, strlen($id)-($i+1));
$final += $num;
}
return $final;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment