Is there a simple way to do this?
I want to pick 3 numbers between 1 and 10 randomly. But I want to make sure there is no chance for the same number showing up.
Correct 4,10,7
Incorrect 4,4,10
can any one tell me how can i do it?
thanks
<?php
function getRandomNumber($min, $max) {
static $alreadyExists = array();
// Avoid endles-loop
if(count($alreadyExists) < ($max+$min)) {
do {
$i = rand($min, $max);
} while(isset($alreadyExists[ $i ]));
$alreadyExists[ $i ] = true;
return $i;
} else {
return null;
}
}
for($i=0; $i<20; $i++) {
var_dump(getRandomNumber(0, 10));
}
<?php
$randNums = array();
while (3 != count($randNums)) {
$randNums[mt_rand(1, 10)] = null;
}
$randNums = array_keys($randNums);
var_dump($randNums);
?>
<?php
function get_unique_range($count, $min, $max)
{
if (($max - $min + 1) < $count) {
return false;
}
$randNums = array();
while ($count != count($randNums)) {
$randNums[mt_rand($min, $max)] = null;
}
$randNums = array_keys($randNums);
return $randNums;
}
var_dump(get_unique_range(3, 1, 10));
?>
Users browsing this forum: No registered users and 20 guests