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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.