note 32621 added to function.rand
| From: | stuartc1 at rack1 dot php dot net | Date: | Tue, 03 Jun 2003 09:52:30 +0000 |
| Subject: | note 32621 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-49606@lists.php.net to get a copy of this message | ||
Here is a simple function that will produce a list of UNIQUE random numbers within a range.
<?
// set some globals
$s = array();
$n = 12; // the range you require (this will give 1-12)
function set_num() {
global $s, $n;
$add = "yes";
$ran = rand(1, $n);
if(count($s) > 0) {
foreach($s as $sh) {
if($ran == $sh) {
$add = "no";
}
}
}
if($add == "yes") {
$s[] = $ran;
} else {
set_num();
}
}
// call the function as needed
while(count($s) < $n) {
set_num();
}
// just output a list seperated by whitespace
foreach($s as $sh) {
echo $sh." ";
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32621
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32621&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32621&report=yes