note 81995 deleted from function.mt-rand by nlopess

From: Date: Sun, 23 Mar 2008 11:23:18 +0000
Subject: note 81995 deleted from function.mt-rand by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137360@lists.php.net to get a copy of this message
Note Submitter: andrei@nova ---- Here's a simple function i've made for generateing unique random numbers. Be carefull, the function will go into an infinite loop if you request more unique numbers then the given range (ex. if you call unic(1, 5) five times it's ok, but the 6'th time it will go into an infinite loop). $unic_arr = array(); //the array in witch the used numbers are stored. function unic($min, $max) { global $unic_arr; $rand = mt_rand($min, $max); $tf = 1; while(true) { if(!in_array($rand, $unic_arr)) { $tf = 0; break; } else $rand = mt_rand($min, $max); } array_push($unic_arr, $rand); return $rand; } //to call the function use: unic($min, $max); //ex. unic(1000, 9999);

« previous php.notes (#137360) next »