Skip to content Skip to sidebar Skip to footer

How To Generate Random Numbers/letters With PHP/Javascript

I have looked all over but I can't find it. I need a script to generator random captial letters and numbers at the click of a button. I need to have the dash ' - ' between every 4

Solution 1:

There are many ways to generate random 'things':

  1. rand function
  2. microtime function
  3. uniqid function

Then if you need letters and number you can use md5 function to generate a hash from one of the above.

You can then change the md5 hash to upper case and get what you want (lenght) and insert '-' for every 4 characters.


Solution 2:

//generate 4 characters random string
 function generateRandomString($length = 4, $letters = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM'){
    $s = '';
    $lettersLength = strlen($letters)-1;

    for($i = 0 ; $i < $length ; $i++)
    {
        $s .= $letters[rand(0,$lettersLength)];
    }

    return $s;
} 

echo generateRandomString()."-".generateRandomString();

Fastest way. Function can be improved though... write it at hand, right now. :)


Post a Comment for "How To Generate Random Numbers/letters With PHP/Javascript"