Jump to content

Generating random alphanumeric code


Go to solution Solved by denno020,

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!

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);
Edited by Eiolon
Link to comment
Share on other sites

  • Solution

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.



Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

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

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.