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)

Posted By: anke909 on December 24, 2018

Thanks for the ideas here I found here very important informations open control panel windows 10 because before come here I was too much confuse to clear the concept of the variables and its uses also but now I can say this is very easy for understand.

Posted By: worldwa on November 1, 2019

function encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { // can't handle numbers larger than 2^31-1 = 2147483647 $str = ''; do { $i = $val % $base; $str = $chars[$i] . $str; $val = ($val - $i) / $base; } while($val > 0); return $str; }

function decode($str, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { $len = strlen($str); $val = 0; $arr = arrayflip(strsplit($chars)); for($i = 0; $i < $len; ++$i) { $val += $arr[$str[$i]] * pow($base, $len-$i-1); } return $val; }

echo encode(2147483647); // outputs 2lkCB1

Posted By: worldwa on November 1, 2019

google [url=https://www.google.com]google[/url] https://www.google.com http://www.google.com

You need to login to post a comment.