...

View Full Version : 5 unique random number in an array



anshul
06-16-2005, 08:33 AM
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 (http://www.mediasworks.com/webstory/cghost/blood.htm)

SeeIT Solutions
06-16-2005, 08:40 AM
$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
true; written on a line by itself.

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

anshul
06-16-2005, 10:47 AM
Thanx, that worked but as indexes of array is not sequential; I added

while(list($key, $value) = each($random))
$random_[] = $value;

Isn't PHP has a function for this also?

guideseeq IT Workz (http://www.guideseeq.com/detail.htm)

delinear
06-16-2005, 11:43 AM
You mean you want to turn something like this:


Array
(
[0] => 7
[2] => 3
[5] => 2
[6] => 6
[12] => 4
)
into this:

Array
(
[0] => 7
[1] => 3
[2] => 2
[3] => 6
[4] => 4
)

If so, you can use the array_values() function:

$random = array_values($random);

anshul
06-16-2005, 12:14 PM
Yes. Excellent PHP functions :thumbsup: Thank you both :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum