View Full Version : which one is better?

03-11-2010, 05:44 AM
Which one do you prefer among the two?

function genRandomNo($length = 5){
$string = substr(md5(uniqid(rand(), true)), 0, $length);
return $string;

function genRandomNo($length = 5){
$string = substr(md5(microtime() * mktime()), 0, $length);
return $string;

also you can suggest alternatives.


03-11-2010, 06:36 AM
Generate a random alphanumeric string of any length:

function random_string( $length = 5 )
mt_rand(), TRUE
), ceil(
( int ) $length / 32
), 0, ( int ) $length

What this does is generate an MD5 hash using uniqid()... but it repeats the string back to back to compensate for the requested length.

For example, an MD5 hash is 32 characters in length. So if the requested $length is 37, it will take the ceiling of 37/32, which is 2. Multiply that by 32 and you have 64 characters... so you'll always have enough to work with.

Then it shuffles that using str_shuffle() and reduces it using substr().

Could be seen as an overkill, benchmarks consistently came in between 0.0001 and 0.0003 seconds.

03-11-2010, 02:15 PM
benchmarks consistently came in between 0.0001 and 0.0003 seconds.


03-11-2010, 03:49 PM
Versus nothing.

.0001 isn't the fastest processing on planet earth, but try getting a random string of, ohhh let's say, 56 characters with those two original functions. Not happening.

When you creep up into 5,000 characters, that's when you start seeing times between .0002 and .0004. 50,000 characters? Between .0018 and .0022.

It demonstrates what I see as a fair trade-off between "typically-lengthed" random strings, but without the 32 character limit of an MD5 hash length.

The first one by the OP was clocked at 2.0e-5, which is wayyy faster, but limited to 32 characters.

If you will never need a random string of more than 32 characters, then either one of those would work. I'd prefer uniqid() over multiplying microtime() though. And if you continue to use rand(), consider swapping it out for mt_rand(), which is 4-times faster.

03-11-2010, 04:07 PM
Thanks for the elaboration; very interesting :)