Home arrow PHP arrow Page 3 - Mastering WHILE Loops for PHP and MySQL

Generating Unique Random Numbers Using WHILE Loops - PHP

Do you want to learn how to handle PHP WHILE loops? WHILE loops are one of the most powerful features as well as the easiest loop available to any PHP/MySQL developer. They enable us to shorten repetitive tasks for a highly useful application. This tutorial gives examples of WHILE loops in PHP/MySQL that beginner and novice developers can use as a quick reference for building similar loops in their applications.

  1. Mastering WHILE Loops for PHP and MySQL
  2. Using WHILE Loops as Counters
  3. Generating Unique Random Numbers Using WHILE Loops
  4. Constructing Trigonometric Tables Using WHILE Loops
  5. Retrieving All Rows in a MySQL Table Using WHILE Loops
By: Codex-M
Rating: starstarstarstarstar / 9
October 27, 2009

print this article



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: 




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:


//create array

$randomarray = array();

//initiate counter


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


//number is not in array, store the number in array and increment counter





//echo all results inside the array

while (list($key,$value) = each($randomarray)) {

echo $value;

echo '<br />';



>>> More PHP Articles          >>> More By Codex-M

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: