Eiolon Posted July 13, 2013 Share Posted July 13, 2013 I am trying to generate a random 4 character alphanumeric code. For some reason my script is sometimes generating a 3 character code, though most the time it is doing a 4 character. Thanks for your help! <?php function randomCode() { $length = 4; $characters = '2345678ABCDEF'; $code= ''; for ($p = 0; $p < $length; $p++) { $code.= $characters[mt_rand(0, strlen($characters))]; } return $code; } echo randomCode($code); ?> Link to comment https://forums.phpfreaks.com/topic/280128-generating-random-alphanumeric-code/ Share on other sites More sharing options...
denno020 Posted July 13, 2013 Share Posted July 13, 2013 For starters, how come you're calling the randomCode() function with a parameter? You don't actually define that parameter in the function signature The problem you're having is that strlen($characters) will return 13, however the last entry in the string, the 'F', is at position 12, so you need to make it string length subtract 1: $code .= $characters[mt_rand(0, (strlen($characters)-1))] That should help you out. Denno Link to comment https://forums.phpfreaks.com/topic/280128-generating-random-alphanumeric-code/#findComment-1440616 Share on other sites More sharing options...
Eiolon Posted July 13, 2013 Author Share Posted July 13, 2013 Thanks for your help, I understand now. Link to comment https://forums.phpfreaks.com/topic/280128-generating-random-alphanumeric-code/#findComment-1440617 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.