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. Link to comment https://forums.phpfreaks.com/topic/167470-solved-problem-with-random-number-loop/ 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. Link to comment https://forums.phpfreaks.com/topic/167470-solved-problem-with-random-number-loop/#findComment-883126 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). Link to comment https://forums.phpfreaks.com/topic/167470-solved-problem-with-random-number-loop/#findComment-883142 Share on other sites More sharing options...
loquela Posted July 28, 2009 Author Share Posted July 28, 2009 Thanks for that guys! Link to comment https://forums.phpfreaks.com/topic/167470-solved-problem-with-random-number-loop/#findComment-885175 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.