note 49821 deleted from function.rand by felipe

From: Date: Sun, 30 Dec 2007 18:42:19 +0000
Subject: note 49821 deleted from function.rand by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134408@lists.php.net to get a copy of this message
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)); ?>

« previous php.notes (#134408) next »