Reputation: 1804
I need to work out a way to create 10,000 non-repeating random numbers in PHP, and then put it into database table. Number will be 12 digits long.
What is the best way to do this?
Upvotes: 0
Views: 4389
Reputation: 2923
This assumes that you can generate a 12 digit random number without problems (use getrandmax() to see how big you can get....according to php.net on some systems 32k is as large a number as you can get.
$array = array();
while(sizeof($array)<=10000){
$number = mt_rand(0,999999999999);
if(!array_key_exists($number,$array)){
$array[$number] = null;
}
}
foreach($array as $key=>$val){
//write array records to db.
}
You could use either rand() or mt_rand(). mt_rand() is supposed to be faster however.
Upvotes: -1
Reputation: 13816
Read e.g. 40000 (=PHP_INT_SIZE * 10000) bytes from /dev/random
at once, then split it, modularize it (the %
operator), and there you have it.
Then filter it, and repeat the procedure.
That avoids too many syscalls/context switches (between the php runtime, the zend engine, and the operating system itself - I'm not going to dive into details here).
That should be the most performant way of doing it.
Upvotes: 3
Reputation: 2941
Generate 10000 random numbers and place them in an array. Run the array through array_unique
. Check the length. If less than 10000, add on a bunch more. Run the array through array_unique
. If greater than 10000, then run through array_slice
to give 10000. Otherwise, lather, rinse, repeat.
Upvotes: 1
Reputation: 60498
At 12 digits long, I don't think the possibility of getting repeats is very large. I would probably just generate the numbers, try to insert them into the table, and if it already exists (assuming you have a unique constraint on that column) just generate another one.
Upvotes: 4