random x digit number generation
Moderator: General Moderators
random x digit number generation
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
e.g. 03840441
Cheers
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
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:
On my local system:
Code: Select all
[feyd@home]>php -r "var_dump(getrandmax(), mt_getrandmax());"
int(32767)
int(2147483647)Code: Select all
for($i=0;$i<$yourStringLength;++$i)
{
$random_digit .= rand(0,9);
}Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
- nickman013
- Forum Regular
- Posts: 764
- Joined: Sun Aug 14, 2005 12:02 am
- Location: Long Island, New York
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.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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
- nickman013
- Forum Regular
- Posts: 764
- Joined: Sun Aug 14, 2005 12:02 am
- Location: Long Island, New York
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA