Jump to content


This topic is now archived and is closed to further replies.


generating random alpha-numeric string

Recommended Posts

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 :(

Share this post

Link to post
Share on other sites
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:

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

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:

[code]for ($i = 1; $i <= $length; ++$i)
  $index = mt_rand(0, 61);
  $temp_code .= $string{$index};
  $temp_code .= $array[$index];
$final_code = $temp_code;[/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.

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.