note 84335 deleted from function.rand by tularis
| From: | tularis@php.net | Date: | Wed, 09 Jul 2008 21:49:10 +0000 |
| Subject: | note 84335 deleted from function.rand by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-141335@lists.php.net to get a copy of this message | ||
Note Submitter: mlibazisi at gmail dot com
----
A simple class to generate unique random values:
class UniquelyRandom{
private static $alreadyGenerated = array();
public function urand($min = NULL, $max = NULL)
{
$range = ($min) && ($max) ? ($max - $min) + 1 : NULL; //inclusive
$rangeList = array();
do{
$randValue = ($range) ? rand($min, $max) : rand();
$key = md5($randValue);
if(count($rangeList) == $range) return 'All values between ' . $min . ' and '
. $max . ' have been exhausted';
if($range) $rangeList = array_merge($rangeList, array($key => $randValue));
}while(self::$alreadyGenerated[$key]);
self::$alreadyGenerated[$key] = $randValue;
return $randValue;
}
}
$rand = new UniquelyRandom();
/* here is an example of how to use the code
//Without a range
$number = $rand->urand();
echo $number;
//using a range
$number = $rand->urand(3, 14);
echo $number;
*/