Jump to content

[SOLVED] Problem with random number loop


loquela

Recommended Posts

 

Hi there,

 

while ($row_artists = mysql_fetch_assoc($artists)) {
srand(time());
$random = (rand(1,9));

echo ("<p>Artist: ".$row_artists['jm_artist']." | Random number: ".$random."</p>");
}

 

The above code lists my artists fine, and each time I run the script a different random number is generated. However, for some reason the random number is not being reset for each row - the random number next to each artist is the same. Any ideas why?  :confused:

 

Thanks in advance,

 

Si.

 

Link to comment
https://forums.phpfreaks.com/topic/167470-solved-problem-with-random-number-loop/
Share on other sites

That would be because you're seeding the random number generator each time the loop runs. The time function returns the number of seconds since 1st January 1970 (Unix Epoch) and since the the loop will take under 1 second to run, it gets seeded with the same number each time. If you're not sure why this is a problem I suggest reading up about pseudo-random numbers.

 

The solution? Assuming you're using a version of PHP greater than 4.2.0, you don't need to seed at all because, as the manual page says, it's done automatically. Using an antiquated version? Then you just seed once prior to the loop running.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.