note 83358 added to function.mt-rand
| From: | don_knotts at hotmail dot com | Date: | Thu, 22 May 2008 10:57:02 +0000 |
| Subject: | note 83358 added to function.mt-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-139607@lists.php.net to get a copy of this message | ||
Here is a simple way to get UNIQUE random numbers, because if you are wanting random numbers, say,
between 1 and 10, then you will get duplicates very often, so this function takes care of that.
However, for a very large amount of numbers, this could be very slow. I use this to generate random
pictures on a webpage so that I don't get the same picture twice, but it only picks from about
50 pictures.
// **************************************************
// generate UNIQUE random numbers between min and max
// uses the updated mt_rand() php function
// 'min' = minimum random number
// 'max' = maximum random number
// 'count' = how many numbers in the array
// returns array with random numbers
// error msg if count is greater than max
// **************************************************
function generateUniqueRandoms($min, $max, $count) {
if($count > $max) { // this prevents an infinite loop
echo "ERROR: The array count is greater than the random number maximum.<br>\n";
echo "Therefore, it is impossible to build an array of unique random
numbers.<br>\n";
break;
}
$numArray = array();
for($i = 0; $i < $count; $i++) {
$numArray[$i] = mt_rand($min,$max); // set random number
for($j = 0; $j < $count; $j++) // for each number, check for duplicates
if($j != $i) // except for the one you are checking of course
if($numArray[$i] == $numArray[$j]) {
$numArray[$i] = mt_rand(1,10); // if duplicate, generate new random
$j = 0; // go back through and check new number
}
}
return $numArray;
} // end generateUniqueRandoms() ----------------------
// ****************************************************
----
Server IP: 64.71.164.2
Probable Submitter: 68.47.206.149
----
Manual Page -- http://www.php.net/manual/en/function.mt-rand.php
Edit -- https://master.php.net/note/edit/83358
Del: integrated -- https://master.php.net/note/delete/83358/integrated
Del: useless -- https://master.php.net/note/delete/83358/useless
Del: bad code -- https://master.php.net/note/delete/83358/bad+code
Del: spam -- https://master.php.net/note/delete/83358/spam
Del: non-english -- https://master.php.net/note/delete/83358/non-english
Del: in docs -- https://master.php.net/note/delete/83358/in+docs
Del: other reasons-- https://master.php.net/note/delete/83358
Reject -- https://master.php.net/note/reject/83358
Search -- https://master.php.net/manage/user-notes.php