note 50417 added to function.mt-rand

From: Date: Sun, 27 Feb 2005 23:00:48 +0000
Subject: note 50417 added to function.mt-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-85647@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.mt-rand.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+50417 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50417&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50417&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50417&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50417&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50417&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+50417&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#85647) next »