# Thread: Generate 6 unique random numbers with PHP?

1. ## Generate 6 unique random numbers with PHP?

How to generate a set of 6 random numbers
- range from 1 to 100
- each number must be unique
- no number to be repeated.
?

2. PHP Code:
``` \$randarray = array(); for(\$i = 1; \$i <= 6; ) {     unset(\$rand);     \$rand = rand(1, 100);     if(!in_array(\$rand, \$randarray))     {         \$randarray[] = \$rand;         \$i++;     } } print_r(\$randarray);  ```
Cheers.

3. thanks a lot.

Your script print out the results in this format

Array ( [0] => 37 [1] => 42 [2] => 43 [3] => 36 [4] => 41 [5] => 26 )

May I know how can i remove the words: Array, [0] =>, [1] => .....

and just print out the numbers only?

4. PHP Code:
``` for(\$i = 1; \$i <= 6; ) {     unset(\$rand);     \$rand = rand(1, 100);     if(!in_array(\$rand, \$randarray))     {         echo \$rand, ' ';         \$i++;     } }  ```
Gives on trial: 83 6 6 82 45 46 (er... random eh... and two 6's, hehe).
Might I suggest you look up the print_r() function see what it does also.

5. PHP Code:
``` \$randarray = array(); for(\$i = 1; \$i <= 6; ) {     unset(\$rand);     \$rand = rand(1, 100);     if(!in_array(\$rand, \$randarray))     {         \$randarray[] = \$rand;         \$i++;     } }  \$randstr = implode(", ", \$randarray); echo \$randstr;  ```

6. [nit-picking]Why bother storing it in the \$randarray in the first place? That's just more work than is necessary to achieve the desired result.[/nit-picking]

7. Originally Posted by timnz
[nit-picking]Why bother storing it in the \$randarray in the first place? That's just more work than is necessary to achieve the desired result.[/nit-picking]
Not true. Notice the in_array so that you don't get two of the same numbers? You need an array for that.

8. Oops, didn't see that.

Why the hell did I post what I did? My brain must have been majorly messed up... it was last day of term.... I had had three assignments/projects due the day before. I think I'll use them as my excuses, and it was "late" at night.

I feel stupid now.

9. BlueFire2k5 and timnz, I want to say thank you for the help. You guys are wonderful. Thanks.

#### Posting Permissions

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