NYCPHP Meetup

NYPHP.org

[nycphp-talk] generate random unique 8-digit number

David Krings ramons at gmx.net
Mon Mar 9 22:32:11 EDT 2009


chad qian wrote:
> Hi,
> I need to generate random 8-digit numbers continuously.And no 
> duplication among all those numbers.In other word,every single 8-digit 
> number must be unique.How to do php programming?
>  
> Thanks a lots!
>  
> chad

How random are you aiming for? As far as I know none of the programming 
languages and computer systems have true random number generators. They all 
follow some algorithm that provides sufficiently random numbers, but some are 
generated more often then others.
Another question is also how many of these numbers do you need in the given 
context? What you can always do is use PHP's random number generator mt_rand 
with the min and max value set so that you always get an 8 digit number. So 
that would be $random = mt_rand(10000000,99999999). What you can do is write 
the numbers to a table that has that field keyed or even an array. That way 
you get an error if it is already in the table or array. And if you get an 
error you go ahead and try again. I recommend to add a counter in and eitehr 
give up after 20 tries or wipe the table and start from scratch. Otherwise you 
have PHP crunching random numbers for five hours just to find the one that is 
still missing. Which brings me back to the question about the amount of 
numbers you need.

Is that what you are looking for? I got most of that from Google and the PHP 
manual.....

David





More information about the talk mailing list