Jump to content


Photo

generating random alpha-numeric string


  • Please log in to reply
1 reply to this topic

#1 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 05 April 2006 - 02:40 AM

a client of mine needs an application to maintain product for their ecommerce site. each product requires a unique alpha-numeric code. since my client and their customers have no need to actually see this code we'd prefer to have it automatically generated every time a new product is created. We'll probably want it to be a fixed number of characters...possibly 8-10. Can someone point me in the right direction? I'm not finding what i need at php.net :(



#2 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 05 April 2006 - 03:37 AM

there are a few ways of doing this. first off, you could define either a string or an array containing a series of characters that you want to allow in the final code; in this case, alphanumerics:

$string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$array = array_merge(range(0, 9), range('A', 'Z'), range('a', 'z'));

i'm not sure if that $array statement will come out to what you want, i haven't used range() much. may want to test it before using it for sure.

then, you simply select a random number between 0 and 61 (since there are 62 characters in each) a given number of times and append the character from either the string or the array onto the code:

for ($i = 1; $i <= $length; ++$i)
{
  $index = mt_rand(0, 61);
  $temp_code .= $string{$index};
  OR
  $temp_code .= $array[$index];
}
$final_code = $temp_code;

where $length can be replaced by the length of code you want. note that OR is not actual code, it's just to say that you choose one or the other depending on whether you use an array or string to store the "salt" (series of characters).

as for ensuring that it is unique, i would just check it against the list of current codes. i don't think there's a more efficient way of ensuring uniqueness.

hope this helps.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users