Reputation: 387
I am trying to display random banners on my page to do this i have a function which gives me a random number and depending on the number i display the banner the problem is that sometimes i get the same number so when the page refreshes the same banner is displayed. I would like to displaye different banner on each page refresh.
Im using the following code to get the random number:
function &UniqueRands($min, $max, $keys){
static $returnme = array();
while(in_array($x = rand($min,$max),$returnme));
$returnme[] = $x;
if($keys < count($returnme)-1 && $keys < ($max-$min))
UniqueRands($min, $max, $keys);
return $returnme;
}
$rands = &UniqueRands(1, 3, 1);
foreach ($rands as $num) {
echo "$num\n";
}
and after i get the random number i just do
if ($num=1){
//display banner 1
}
...
What I am doing wrong and I would be happy to hear any other ideas. Thanks.
Upvotes: 1
Views: 1125
Reputation: 3275
the problem is that sometimes i get the same number so when the page refreshes the same banner is displayed
Depending on how many banners you have, that is entirely possible. Suppose you have 4 banners, the chances of getting the same two in a row are 1/4.
If you really don't want to the same banner to be displayed twice in a row, you actually need to make it less random rather than more. Store the last banner shown in a cookie or something, then when picking the next banner to show make sure you don't show that one.
Of course, as CanSpice says if you have 4 banners and the user looks at 5 pages then you are going to have to show one banner more than once. But using this method you can stop them seeing the same banner twice in a row at least.
Upvotes: 2
Reputation: 1567
mt_rand[1] supposedly produces better ("more random") pseudo-random numbers, compare [2]
[1] http://de.php.net/manual/en/function.mt-rand.php
[2] http://tjl.co/blog/code/followup-php-rand-vs-mt_rand/
Upvotes: 0
Reputation: 3192
Which version of PHP are you using? Since 4.2 rand()
function is seeded automatically, but if you are using older one, you have to use srand()
function before calling rand()
function to initialize random number generator. Or maybe mt_rand()
will help.
Upvotes: 0