Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

real random number

I have 5 jpg, named 01.jpg, 02.jpg..... 05.jpg. I have a little script that generate a number between 1-5 and shop up the jpg associated with it.... fine... But each time i reload the page, the picture is "supposed" to be random, and so different, but only 5 image, i get the same image on reload "a lot more" that i what to.... so the question is... Hot to make sure, on the reload of the web page the random number should be between 1-5 and NOT the same as it was the second before... so with that i will be sure to see on 5 consecutive reload the 5 picture at least !....

php of ajvascript please

here is the code :

<style type="text/css">
#photo { background-image: url(http://www.something/pano-0<?php echo mt_rand (1,5) ?>.jpg); } 
</style>

note: for people that tell it's a sequence... no i like the random... at least do not choose the same

let say if #3 show, you random... and you can have 1,2,3,4,5, let get 2, if 3, re-random!

like image 287
menardmam Avatar asked Jun 12 '26 14:06

menardmam


2 Answers

Very similar to @Jon Snyder's answer, but using $_SESSION instead of $_GET:

<?php
    // initialize session
    session_start();

    // array of possible images
    $images = array('01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg');

    // check if user has seen an image before
    $last = isset($_SESSION['last_img']) ? $_SESSION['last_img'] : -1;

    // generate a random number that isn't the same as $last
    do { $num = rand(0, count($images)-1); } while ($num == $last);

    // display image
    echo '<img src="' . $images[$num] . '">' . PHP_EOL;

    // save last image in $_SESSION
    $_SESSION['last_img'] = $num;
?>
like image 135
drudge Avatar answered Jun 15 '26 05:06

drudge


Roll a die. Do you ever get the same number twice or even three times in a row? Do you doubt the die's randomness?

With 5 images, you have a 20% chance that the image this time will be the same as the last one. You don't want a random distribution. You just want to rotate them every time. We promise not to tell your users it's not truly random ;)

like image 28
Karl Bielefeldt Avatar answered Jun 15 '26 03:06

Karl Bielefeldt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!