note 49821 added to function.rand
| From: | php dot net at dannysauer dot com | Date: | Wed, 09 Feb 2005 14:47:07 +0000 |
| Subject: | note 49821 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-84717@lists.php.net to get a copy of this message | ||
Actually, if you want 2 different random numbers, you should probably use a while loop. This is
quicker and doesn't have the possibility of running into a recursive function limit.
<?php
function fn_arrRandom($min, $max){
// generate two random numbers
$iRandom1 =0;
$iRandom2 = 0;
// compare them
while ($iRandom1 == $iRandom2){
// the numbers are equal, try again
$iRandom1 = rand($min, $max);
$iRandom2 = rand($min, $max);
}
// they're not equal - go ahead and return them
return array($iRandom1, $iRandom2);
}
print_r(fn_arrRandom(3, 13));
?>
At that point, we may as well write a function that returns an arbitrary number of differing random
numbers:
<?php
function random_array($min, $max, $num){
$range = 1+$min-$max;
// if num is bigger than the potential range, barf.
// note that this will likely get a little slow as $num
// approaches $range, esp. for large values of $num and $range
if($num > $range){
return false;
}
// set up a place to hold the return value
$ret = Array();
// fill the array
while(count($ret)) < $num){
$a = false; // just declare it outside of the do-while scope
// generate a number that's not already in the array
// (use do-while so the rand() happens at least once)
do{
$a = rand($min, $max);
}while(in_array($ret, $a));
// stick the new number at the end of the array
$ret[] = $a;
}
return $ret;
}
print_r(random_array(3, 13, 5));
?>
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+49821
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49821&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49821&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49821&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49821&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49821&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+49821&report=yes
Search -- http://master.php.net/manage/user-notes.php