note 71704 added to function.mt-rand

From: Date: Tue, 12 Dec 2006 17:47:41 +0000
Subject: note 71704 added to function.mt-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-120553@lists.php.net to get a copy of this message
If you need a random number but not the numbers in a specified array, you may use my function below: <?php function mt_rand_n($min,$max,$disallowed) { // $a must be an array if (!is_array($disallowed)) return false; // Create an array with the numbers from $min to $max // without the numbers in $disallowed. // - range() to create an array with the numbers from $min to $max // - array_diff() to create the allowed numbers // - since array_diff() doesn't change the keys, we've to change them with // array_values(), to get an normal order (0,1,2,3 ... ) $numbers = array_values(array_diff(range($min,$max),$disallowed)); // size of $numbers must be greater than 0 if (count($numbers) < 1) return false; // create random number and return it return $numbers[mt_rand(0,count($numbers) - 1)]; } // Example: $min = 0; $max = 10; $disallowed = array(0,1,2,3,4,9,10); // the numbers 1,2,3,6,7, and 8 are disallowed for ($i = 0; $i < 100; $i++) var_dump(mt_rand_n($min,$max,$disallowed)); ?> I hope it helps someone ... Btw. here's the "un-comment" function: <?php function mt_rand_n($min,$max,$disallowed) { if (!is_array($disallowed)) return false; $numbers = array_values(array_diff(range($min,$max),$disallowed)); if (count($numbers) < 1) return false; return $numbers[mt_rand(0,count($numbers) - 1)]; } ?> Have fun :) ---- Server IP: 194.153.94.10 Probable Submitter: 80.219.154.129 ---- Manual Page -- http://www.php.net/manual/en/function.mt-rand.php Edit -- https://master.php.net/note/edit/71704 Del: integrated -- https://master.php.net/note/delete/71704/integrated Del: useless -- https://master.php.net/note/delete/71704/useless Del: bad code -- https://master.php.net/note/delete/71704/bad+code Del: spam -- https://master.php.net/note/delete/71704/spam Del: non-english -- https://master.php.net/note/delete/71704/non-english Del: in docs -- https://master.php.net/note/delete/71704/in+docs Del: other reasons-- https://master.php.net/note/delete/71704 Reject -- https://master.php.net/note/reject/71704 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#120553) next »