Reputation: 8882
I'm running rand() 3 times, and I want to exclude the first two results from the possibilities of the function. Like if it hit 1 and 5, I want the next rand() to exclude 1 and 5 from its range. How would I do this?
Upvotes: 3
Views: 5889
Reputation: 4058
If you want to generate three unique random(ish) numbers, you could use:
$totalNumsNeeded = 3;
$randoms = array();
while (count($randoms) < $totalNumsNeeded) {
$random = rand($min, $max);
if (!in_array($random, $randoms)) {
$randoms[] = $random;
}
}
Upvotes: 1
Reputation: 736
$last[];
for ($i = 0; $i < 10; $i++) {
$min = getLow($last);
$max = getHigh($last);
$myrand = rand ( $min, $max )
$last[i] = $myrand;
}
You will need to build the two functions to itterate through the $last array and return the variables you want it to return... or if you are only looking for the last two, you could initialize $min and $max outside of the loop and set them on each itteration. This will continually tighten your random range though.
Another solution may be
$last;
While (true) {
$myRand = rand();
if ($myRand != $last) {
$last = $myRand;
break;
}
}
Upvotes: 0
Reputation: 6992
How about:
do {
$rand_number = rand();
}while(in_array($rand_number, array(1,5));
Upvotes: 5