# Non-duplicating random numbers

• Apr 23, 2013, 09:35
fredep57
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
• Apr 23, 2013, 10:02
John_Betong
Try searching for "php manual rand()" and also for mt_rand()
• Apr 23, 2013, 10:14
K. Wolfe
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);```
• Apr 23, 2013, 11:03
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);
• Apr 23, 2013, 11:26
K. Wolfe
Quote:

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.