Posted By

jmiller on 10/31/09


Tagged

encode unique id decode base62


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

niklasm
bug5


Base62 Encode / Decode


 / Published in: PHP
 

URL: http://programanddesign.com/php/base62-encode/

If you have large integers and you want to shrink them down in size for whatever reason, you can use this code. Should be easy enough to extend if you want even higher bases (just add a few more chars and increase the base).

  1. function encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  2. // can't handle numbers larger than 2^31-1 = 2147483647
  3. $str = '';
  4. do {
  5. $i = $val % $base;
  6. $str = $chars[$i] . $str;
  7. $val = ($val - $i) / $base;
  8. } while($val > 0);
  9. return $str;
  10. }
  11.  
  12. function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  13. $len = strlen($str);
  14. $val = 0;
  15. $arr = array_flip(str_split($chars));
  16. for($i = 0; $i < $len; ++$i) {
  17. $val += $arr[$str[$i]] * pow($base, $len-$i-1);
  18. }
  19. return $val;
  20. }
  21.  
  22. echo encode(2147483647); // outputs 2lkCB1

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: simoneast on February 13, 2012

Found this snippet from a link from StackOverflow.

If you want to encode larger numbers (like I did) you need to replace... $val % $base ...with... fmod($val, $base)

You need to login to post a comment.