note 54585 added to function.rand
| From: | markatmmprodotde at osu1 dot php dot net | Date: | Fri, 08 Jul 2005 14:14:22 +0000 |
| Subject: | note 54585 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-91673@lists.php.net to get a copy of this message | ||
I needed to generate a random array of different(!) numbers, i.e. no number in the array should be
duplicated. I used the nice functions from phpdeveloper AT o2 DOT pl but it didn't work as I
thought.
So I varied it a little bit and here you are:
function RandomArray($min,$max,$num) {
$ret = array();
// as long as the array contains $num numbers loop
while (count($ret) <$num) {
do {
$a = rand($min,$max);
//
#echo $a."<br />";
}
// check if $a is already in the array $ret
// if so, make another random number
while (in_array($a,$ret));
// add the new random number to the end of the array
$ret[] = $a;
}
return($ret);
}
// generate an array of 3 numbers between 10 and 19
$ret = randomArray(10,19,3)
echo $ret[0]."-".$ret[1]."-".$ret[2];
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54585
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54585&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54585&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54585&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54585&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54585&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54585&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54585&report=yes
Search -- http://master.php.net/manage/user-notes.php