note 84343 deleted from function.rand by danbrown

From: Date: Wed, 05 Nov 2008 15:36:19 +0000
Subject: note 84343 deleted from function.rand by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146168@lists.php.net to get a copy of this message
Note Submitter: Prince Mabandla ---- Okay, here is the final version of a simple function to generate random (but unique) numbers. As I said earlier, it will use less memory when an explicit range is supplied, (the smaller the better). You could always customize it, e.g. the hash algorithm, the return value once it has exhausted the values within a supplied range, etc. function urand($min = NULL, $max = NULL){ static $alreadyGenerated = array(); $range = ($min && $max) ? ($max - $min) + 1 : NULL; do{ $randValue = ($range) ? rand($min, $max) : rand(); $key = md5($randValue); if(count($rangeList) == $range) return NULL; if($range) $rangeList[$key] = $randValue; }while($alreadyGenerated[$key]); unset($rangeList); $alreadyGenerated[$key] = $randValue; return $randValue; }

« previous php.notes (#146168) next »