Skip to content

Instantly share code, notes, and snippets.

@Avakulenko
Created January 6, 2016 13:03
Show Gist options
  • Save Avakulenko/6d987acf7c73432bbcd5 to your computer and use it in GitHub Desktop.
Save Avakulenko/6d987acf7c73432bbcd5 to your computer and use it in GitHub Desktop.
function crb_encode_short_ref_code($id) {
// if (!is_int($id)) {
// echo 'not an int';
// }
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ($id == 0) {
return $chars[0];
}
$number = abs($id);
if ($id < 0) {
echo "Can not encode for negative integers";
}
$string = '';
$base = strlen($chars);
while ($number > 0) {
$string .= $chars[$number % $base];
$number = (int) ($number / $base);
}
return strrev($string);
}
function crb_decode_short_ref_code($string) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$stringLength = strlen($string);
$baseLength = strlen($chars);
$id = 0;
for($i = 0; $i < $stringLength; $i++) {
$pos = strpos($chars, $string[$i]);
$id = ($id * $baseLength) + $pos;
}
return $id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment