note 96389 added to function.mt-rand

From: Date: Wed, 24 Feb 2010 15:53:25 +0000
Subject: note 96389 added to function.mt-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-166319@lists.php.net to get a copy of this message
A little useful function to create a random unique number out of an array of unallowed values: <?php function rand_except($min, $max, $except) //function returns a random integer between min and max, just like function rand() does. // Difference to rand is that the random generated number will not use any of the values // placed in $except. ($except must therefore be an array) // function returns false if $except holds all values between $min and $max. { //first sort array values sort($except, SORT_NUMERIC); //calculate average gap between except-values $except_count = count($except); $avg_gap = ($max - $min + 1 - $except_count) / ($except_count + 1); if ($avg_gap <= 0) return false; //now add min and max to $except, so all gaps between $except-values can be calculated array_unshift($except, $min - 1); array_push($except, $max + 1); $except_count += 2; //iterate through all values of except. If gap between 2 values is higher than average gap, // create random in this gap for ($i = 1; $i < $except_count; $i++) if ($except[$i] - $except[$i - 1] - 1 >= $avg_gap) return mt_rand($except[$i - 1] + 1, $except[$i] - 1); return false; } ?> ---- Server IP: 217.160.72.57 Probable Submitter: 91.48.92.12 ---- Manual Page -- http://www.php.net/manual/en/function.mt-rand.php Edit -- https://master.php.net/note/edit/96389 Del: integrated -- https://master.php.net/note/delete/96389/integrated Del: useless -- https://master.php.net/note/delete/96389/useless Del: bad code -- https://master.php.net/note/delete/96389/bad+code Del: spam -- https://master.php.net/note/delete/96389/spam Del: non-english -- https://master.php.net/note/delete/96389/non-english Del: in docs -- https://master.php.net/note/delete/96389/in+docs Del: other reasons-- https://master.php.net/note/delete/96389 Reject -- https://master.php.net/note/reject/96389 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166319) next »