note 84343 added to function.rand

From: Date: Thu, 10 Jul 2008 01:08:38 +0000
Subject: note 84343 added to function.rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-141339@lists.php.net to get a copy of this message
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; } ---- Server IP: 69.147.83.197 Probable Submitter: 71.193.113.21 ---- Manual Page -- http://www.php.net/manual/en/function.rand.php Edit -- https://master.php.net/note/edit/84343 Del: integrated -- https://master.php.net/note/delete/84343/integrated Del: useless -- https://master.php.net/note/delete/84343/useless Del: bad code -- https://master.php.net/note/delete/84343/bad+code Del: spam -- https://master.php.net/note/delete/84343/spam Del: non-english -- https://master.php.net/note/delete/84343/non-english Del: in docs -- https://master.php.net/note/delete/84343/in+docs Del: other reasons-- https://master.php.net/note/delete/84343 Reject -- https://master.php.net/note/reject/84343 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#141339) next »