Page 1 of 1

Auto incremented alphanumeric string.

Posted: Fri Dec 03, 2010 3:23 am
by spedula
I need a way to create a 8 character length string that gets auto incremented every time a new on is created.

it should look something like this mKa8dU01.

I found this on another forum, its for a URL shortener.

Code: Select all

for($counter=0; $counter < 10000; $counter+=1) { 
     $shorturl = ""; 
     $tmp_count = $counter; 
     for($i=5;$i>=0; $i--) { 
       $tmp = floor($tmp_count/pow(36,$i)); 
       $tmp_count -= $tmp*pow(36,$i); 
       if($tmp < 10) { 
     $shorturl .= chr($tmp + 48); 
       } else { 
     $shorturl .= chr($tmp + 87); 
       } 
     } 
}
but I have no idea how to use it or if I can even apply it to what I need. Any care to explain what the above actually does or knows how i can get the results I need?

Thanks

Re: Auto incremented alphanumeric string.

Posted: Fri Dec 03, 2010 11:27 am
by Celauran
spedula wrote:Any care to explain what the above actually does or knows how i can get the results I need?
It creates a six-character $shorturl value using the counter value and powers of 36, then discards it and repeats the process. Ten thousand times. If you removed the for loop, replaced $tmp_count = $counter with a random number, and actually did something with the resulting $shorturl, you might have something you could use.

EDIT: Though if you want it to be auto-incrementing, you can't just throw it a random value. You'll need to start with a given value, record it somewhere, and increment it (and save this incremented value, of course) every time the function is called.