note 50417 deleted from function.mt-rand by bjori

From: Date: Sun, 16 Apr 2006 12:36:30 +0000
Subject: note 50417 deleted from function.mt-rand by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-108265@lists.php.net to get a copy of this message
Note Submitter: solenoid at hotmail dot united dot kingdom ---- Sometimes you need a bunch of unique random numbers and they have to be in a certain small range, here's a simple script that uses an array to remember the numbers generated before: <?php $randomNumbers = array(); // storage array for ($i=0;$i<20;$i++) { $random = mt_rand(0,30); while(in_array($random,$randomNumbers)) { $random = mt_rand(0,30); } array_push($randomNumbers,$random); echo $random; } ?> This way, when the while() function finds that the generated number is already in the storage array, it will automatically generate another one until no same number is found, thus eliminating any possibilities of having multiple same numbers... but still random.

« previous php.notes (#108265) next »