loquela Posted July 26, 2009 Share Posted July 26, 2009 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? Thanks in advance, Si. Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted July 26, 2009 Share Posted July 26, 2009 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. Quote Link to comment Share on other sites More sharing options...
Daniel0 Posted July 26, 2009 Share Posted July 26, 2009 Seeding with the current timestamp also makes the random number predictable (yes, that's an oxymoron). Quote Link to comment Share on other sites More sharing options...
loquela Posted July 28, 2009 Author Share Posted July 28, 2009 Thanks for that guys! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.