Jump to content

generating random alpha-numeric string


bcamp1973

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

Link to comment
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};
  OR
  $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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.