3

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?

4
  • 6
    Then it's not random anymore though. :o) Commented Feb 28, 2011 at 7:34
  • In before xkcd and/or 4. Oh, also, consider mt_rand instead of rand. Commented Feb 28, 2011 at 7:43
  • @Charles You're forgetting Nine, Nine, Nine, Nine, Nine, Nine. Commented Feb 28, 2011 at 8:01
  • Possible duplicate of How to get a random value from 1~N but excluding several specific values in PHP? Commented Jun 3, 2016 at 16:16

3 Answers 3

5

How about:

do {   
    $rand_number = rand();

}while(in_array($rand_number, array(1,5));
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

1 Comment

This is so underrated! :)
0
$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;
  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.