Auto incremented alphanumeric string.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
spedula
Forum Commoner
Posts: 81
Joined: Mon Mar 29, 2010 5:24 pm

Auto incremented alphanumeric string.

Post 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
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Auto incremented alphanumeric string.

Post 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.
Post Reply