bcamp1973 Posted April 5, 2006 Share Posted April 5, 2006 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 :( Quote Link to comment https://forums.phpfreaks.com/topic/6624-generating-random-alpha-numeric-string/ Share on other sites More sharing options...
akitchin Posted April 5, 2006 Share Posted April 5, 2006 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. Quote Link to comment https://forums.phpfreaks.com/topic/6624-generating-random-alpha-numeric-string/#findComment-24066 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.