The above example will not generate unique random numbers. We can still make use of PHP WHILE loops as a counter. But to generate “X” amount of unique random numbers, we will make use of a PHP array. A full discussion of arrays is out of the scope of this article. However, below you will find some good references: http://www.phphelps.com/7_Creating_and_looping_array_in_PHP.shtml http://free.netartmedia.net/PHP/PHP50.html http://www.homeandlearn.co.uk/php/php6p2.html The strategy is to generate a random number and store it in an array. Then we'll let PHP decide whether or not the generated random number is already stored in the array. If it is stored already, it will not be assigned to the array variable, but will generate a random number again. This will ensure that all values stored in an array are unique. After the counter reaches its maximum, PHP will then output all the unique values stored in the array using another WHILE looping statement. Below is the example PHP script that will generate 30 unique (non-repetitive) random numbers between 10 and 50: <?php //create array $randomarray = array(); //initiate counter $i=1; while ($i<=30) { //generate random number $randomnumber = mt_rand(10, 50); //check first if generated random number is in array if not store it to the array if(!(in_array($randomnumber,$randomarray))){ //number is not in array, store the number in array and increment counter $randomarray[]=$randomnumber; $i++; } } //echo all results inside the array while (list($key,$value) = each($randomarray)) { echo $value; echo '<br />'; } ?>
blog comments powered by Disqus |
|
|
|
|
|
|
|