Jump to content

Generating random alphanumeric code


Eiolon

Recommended Posts

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

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

Archived

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

×
×
  • 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.