Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: 5 unique random number in an array

1. ## 5 unique random number in an array

I've wrote this code

\$max = 9;
for(\$i=0; count(\$random)<5; \$i++) {
\$random[\$i]=rand(1, \$max);
for(\$j=0; \$j<count(\$random); \$j++) {
if(\$random[\$i]==\$random[\$j]) {
\$random[\$i]==NULL;
array_pop(\$random);
}
}
}

while(list(\$key, \$value) = each(\$random))
echo \$value . ", ";

Sometimes, I get repeated numbers; please help me, where I've mistaken.
ghost

• PHP Code:
``` \$max = 9; for(\$i=0;count(\$random)<5; \$i++) {     \$rand=rand(1, \$max);     if(!in_array(\$rand,\$random)) {         \$random[\$i]=\$rand;     } }  ```
The repeated numbers came from you not actually comparing them, you used == instead of = which is a compare operation. It was basically the same as having
PHP Code:
``` true;  ```
written on a line by itself.

Also, use php functions where possible rather than doing it yourself.

• Thanx, that worked but as indexes of array is not sequential; I added
Code:
```while(list(\$key, \$value) = each(\$random))
\$random_[] = \$value;```
Isn't PHP has a function for this also?

guideseeq IT Workz

• You mean you want to turn something like this:

Code:
```Array
(
[0] => 7
[2] => 3
[5] => 2
[6] => 6
[12] => 4
)```
into this:
Code:
```Array
(
[0] => 7
[1] => 3
[2] => 2
[3] => 6
[4] => 4
)```
If so, you can use the array_values() function:
PHP Code:
``` \$random = array_values(\$random);  ```

• Yes. Excellent PHP functions Thank you both

•

#### Posting Permissions

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