Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Dec 2008
    Posts
    34
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Question Random Number Gen Length Problem

    Hi,

    I'm using the following code to generate a random 12 digit string. However, for some reason its intermittently creating 11 digit strings.

    function genRandomString() {
    $length = 12;
    $characters = '0123456789ABCDEFGHJKMNPQRSTUVWXYZ';
    $string = '';

    for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
    }

    The last string returned was 3E4P5BFSERB - 11 digits and the time prior to that was VGM5V4GJGGH3 - 12 digits. Is there any reason why its sometimes only returning an 11 digit string?

    Thanks

    Ben

    P.S. I know some letters are missing from the available characters, I removed letters that could be mistaken for numbers, i.e. o = 0, i & l = 1 etc, this way if you hand write the string you can't get it wrong.

  • #2
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,854
    Thanks
    160
    Thanked 2,223 Times in 2,210 Posts
    Blog Entries
    1
    $characters[mt_rand(0, strlen($characters))];
    Array out of bound issue. It should be
    PHP Code:
    $characters[mt_rand(0strlen($characters)-1)]; 
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

  • #3
    New Coder
    Join Date
    Dec 2008
    Posts
    34
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Thumbs up Solved

    Ah I see!

    That seems to have fixed the problem, just test generated 3 more strings, and each was 12 digits.

    Thanks for your help

    Ben


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •