get an array containing random integers between $min and $max integers

Trying to pick up random keys from an array but don’t want any duplicates?
try this

  1.  
  2. <?php
  3. //returns an array of random keys between 2 numbers
  4. function &UniqueRands($min, $max, $keys, $reset=true){
  5.         static $returnme = array();
  6.         if($reset) $returnme = array();
  7.         //while is used to avoid recursive the whole function
  8.         while(in_array($x = rand($min,$max),$returnme));
  9.         $returnme[] = $x;
  10.         //$keys are the number of random integers in the array
  11.         //must not be more than the sub of max – min
  12.         if($keys >= count($returnme) && count($returnme) <= ($max-$min))
  13.            UniqueRands($min, $max, $keys,false);
  14.         return $returnme;
  15. }
  16. //usage
  17. $rands = & UniqueRands(0, 100, 30);
  18. print_r($rands);
  19. //with an array
  20. $vararry = array(‘red’, ‘blue’, ‘green’, ‘yellow’,‘black’);
  21. $rands = & UniqueRands(0, count($vararry)-1, 3);
  22. foreach($rands as $x)
  23.         echo "$vararry[$x],";
  24. ?>
  25.  

Tags : more-36

This entry was posted on Wednesday, March 7th, 2007 at 2:26 pm and is filed under Blog, Solutions. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

 

Leave a Reply


 Top