note 49821 deleted from function.rand by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: php dot net at dannysauer dot com 

----

Actually, if you want 2 different random numbers, you should probably use a while loop.  This is quicker and doesn't have the possibility of running into a recursive function limit.

<?php
function fn_arrRandom($min, $max){
   // generate two random numbers
   $iRandom1 =0;
   $iRandom2 = 0;
   // compare them
   while ($iRandom1 == $iRandom2){
       // the numbers are equal, try again
       $iRandom1 = rand($min, $max);
       $iRandom2 = rand($min, $max);
   }
   // they're not equal - go ahead and return them
   return array($iRandom1, $iRandom2);
}

print_r(fn_arrRandom(3, 13));
?>

At that point, we may as well write a function that returns an arbitrary number of differing random numbers:

<?php
function random_array($min, $max, $num){
   $range = 1+$min-$max;
   // if num is bigger than the potential range, barf.
   // note that this will likely get a little slow as $num 
   // approaches $range, esp. for large values of $num and $range
   if($num > $range){
      return false;
   }
   // set up a place to hold the return value
   $ret = Array();
   // fill the array
   while(count($ret)) < $num){
      $a = false; // just declare it outside of the do-while scope
      // generate a number that's not already in the array
      // (use do-while so the rand() happens at least once)
      do{
         $a = rand($min, $max);
      }while(in_array($ret, $a));
      // stick the new number at the end of the array
      $ret[] = $a;
   }
   return $ret;
}

print_r(random_array(3, 13, 5));
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.