Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP excluding numbers from rand() function

Tags:

php

random

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?

like image 532
AKor Avatar asked Mar 28 '26 19:03

AKor


2 Answers

How about:

do {   
    $rand_number = rand();

}while(in_array($rand_number, array(1,5));
like image 75
cypher Avatar answered Apr 01 '26 09:04

cypher


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;
    }
}
like image 40
Eric G Avatar answered Apr 01 '26 11:04

Eric G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!