1. ## Non-duplicating random numbers

What is the easiest and best way to create a list of random numbers from 1 to n where there are no duplicates?

I do not want to use javascript just php and cannot find any item here that best describes how to do this.

Thanks
E

2. Try searching for "php manual rand()" and also for mt_rand()

3. Code PHP:
```\$RandomNumberCount = 10; // pick 10 random numbers
\$RandomNumbers = array(); //for storing our random numbers
for(\$i = 0; \$i < \$RandomNumberCount; \$i++) { //do current operation \$RandomNumberCount times
while(true) { //loop until break
\$Rand = mt_rand(1, 60); //range of your random number to be generated
if(!array_search(\$Rand, \$RandomNumbers)) { //loop until random number doesnt exist in your collection
array_push(\$RandomNumbers, \$Rand); //save your random number
break; //break loop trying to find unused number
}
}
}
print_r(\$RandomNumbers);```

4. When you don't want duplicates, I find that the simplest method is to fill an array with the range of possible values, then shuffle the array.

\$n = 10;

\$range = range(1, \$n);
shuffle(\$range);

5. Originally Posted by Jeff Mott
When you don't want duplicates, I find that the simplest method is to fill an array with the range of possible values, then shuffle the array.

\$n = 10;

\$range = range(1, \$n);
shuffle(\$range);
And then take \$range[0] to \$range[\$x]? I like it.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•