note 96389 deleted from function.mt-rand by cmb

From: Date: Sun, 31 Mar 2019 08:36:13 +0000
Subject: note 96389 deleted from function.mt-rand by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-210461@lists.php.net to get a copy of this message
Note Submitter: wayne ---- 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; } ?>

« previous php.notes (#210461) next »