I want to generate an ID consisting of alphanumeric characters ([a-z][A-Z][0-9]), but I need someway to make the ID as short as possible, for instance if there is still single digit IDs that have not been used yet I want those used first before it makes a 2 digit one and so on and so forth. I've thought about it and I just can't think of a way to do this. Anyone else know of a way?
function genRandomString($length) { $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } PHP: Called with: $string = genRandomString(5); // 5 represents the character length PHP: You can then do a mysql query to make sure its not in use already, assuming you are storing ID's ?
I can make random sequences. But I want it so it checks to see if the id is already taken and then generates the next id in the sequence. For instance 3 ids have been generated already the ids are (a, b and c). A new id is made and it is d.
I assume they are stored somewhere? In that case, you can just take the last id, convert it to base 62 (10 numbers, 26 lower case, 26 uppercase) ,add one, and convert it back.
<?php function from62($base62) { $base62=strrev($base62); $base10=0; $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for($i=0;$i<strlen($base62);$i++) { $base10+=(strpos($str,$base62{$i}))*pow(62,$i); } return $base10; } function to62($base10) { $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $base62=""; $start=floor(log($base10,62)); for($i=$start;$i>=0;$i--) { $base62.=$str{floor($base10/pow(62,$i))}; $base10%=pow(62,$i); } return $base62; } $last="Asdf"; $new=to62(from62($last)+1); PHP: change the $last variable to the last unique id given, and the $new variable will give you the next in line.
There is only base64 not base62 to my knowledge. Here, try this. <?php base64_encode($value); ?> PHP: Here is how you Decode. <?php base64_decode($value); ?> PHP: Hope i helped, Michael
Base 64 is used to encode text, and uses two additional characters, the slash and the equals sign, which cannot be passed through an url. But except from that: The base 64 encoding of the numbers 0 through 10 are: Which are not the shortest available id's