Jump to content

[SOLVED] trouble with rand()


Kane250

Recommended Posts

I have images stored on my server labeled 1.gif, 2.gif, etc. I'm simply trying to generate a random number and insert it into my print statement that pulls those images into the html. I need three images to display at once.

 

However, each time it chooses a random number, all three variables choose that same random number.

 

Any way I can remedy this? I feel like the solution is really simple..

 

$randomanswer = rand(1,12);
$randomanswer2 = rand(1,12);
$randomanswer3 = rand(1,12);

print ("<img src=images/$randomanswer.gif>");
print ("<img src=images/$randomanswer2.gif>");
print ("<img src=images/$randomanswer3.gif>");

 

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/104486-solved-trouble-with-rand/
Share on other sites

From what I am reading, rand() is always random lol...

 

so to ensure true or close to true randomness, use this code:

 

srand((double)microtime()*1000000); 
$randomanswer = rand(1,12); 
$randomanswer2 = rand(1,12); 
$randomanswer3 = rand(1,12); 

print ("<img src=images/$randomanswer.gif>");
print ("<img src=images/$randomanswer2.gif>");
print ("<img src=images/$randomanswer3.gif>");

 

that should produce a completly different set of pictures... however, your window of 1-12 is pretty narrow and you may very well may end up with 2 of the same pictures...

 

you may want to write a if else statement to stop that from happening...

 

eg:

 


while ($randomanswer2 !== $randomanswer1) {
$randomanswer2 = rand(1,12); 
}

while (($randomeanswer3) !== ($randomanswer1 || $randomanswer2)) {
$randomanswer3 = rand(1,12);
}

 

Give that a shot and post back.. if it works for you, click the solved tab at the bottom left side of the post and let us know! :) GL

 

You can try something like this:

<?php
$rn = array();
while (count($rn) < 3) {
   $x = rand(1,12);
   if (!in_array($x,$rn)) $rn[] = $x;
}
foreach ($rn as $n)
    echo '<img src="images/' . $n . '.gif">';
?>

 

This code makes sure you always get 3 different numbers.

 

Ken

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.