Page 1 of 1

random x digit number generation

Posted: Wed Nov 08, 2006 4:11 am
by sh33p1985
looking to generate a random 8 digit number from 00000000-99999999 inclusive but cant work out how to do it easily.
e.g. 03840441

Cheers

Posted: Wed Nov 08, 2006 4:14 am
by aaronhall
Try rand and str_pad

Posted: Wed Nov 08, 2006 6:25 am
by feyd
Numbers that large can easily be outside the maximum range of the random engine, so you may need multiple calls to rand() or mt_rand()

On my local system:

Code: Select all

[feyd@home]>php -r "var_dump(getrandmax(), mt_getrandmax());"
int(32767)
int(2147483647)

Posted: Wed Nov 08, 2006 9:22 am
by sh33p1985
quite frankly i could shorten that to 6 digits no problem, the main principle is that is random number generated will always bee x digits long.

Posted: Wed Nov 08, 2006 10:23 am
by pickle

Code: Select all

for($i=0;$i<$yourStringLength;++$i)
{
   $random_digit .= rand(0,9);
}

Posted: Wed Nov 08, 2006 6:05 pm
by nickman013
Random numbers arent always reliable... Even though the range of numbers is so great, beleive it or not I had the same number twice. If you are trying to generate unique numbers. Use the persons IP and time stamp, it works perfect.

Posted: Wed Nov 08, 2006 6:17 pm
by pickle
nickman013 wrote:Random numbers arent always reliable... Even though the range of numbers is so great, beleive it or not I had the same number twice. If you are trying to generate unique numbers. Use the persons IP and time stamp, it works perfect.
Good point. Unfortunately, 'perfect' means 100% and neither of our methods are 100%. You're right that mine could generate duplicate ids. Yours could too (technically) if two people from behind the same NAT gateway access the page in the same second. ~sh33p1985: I believe if you incorporate uniqid() into the mix, you should be ok.

Posted: Wed Nov 08, 2006 6:49 pm
by nickman013
lol thats true

Posted: Wed Nov 08, 2006 7:28 pm
by RobertGonzalez
I think the only way to get true uniqueness is to create the number is some way that has been mentioned in this thread, then store it in the database. Check to see if it is in there, and if so, regenerate, else, use it.