0

here the sample case..

i want to display banner randomly by percentage based on visitor hits. for example i want to display ads 70% of visitor hits.. the problem is we don't know how many visitor is.

if it make easier we have set percentage 10%, 20%, 30% ... 100%

  • and maybe also possible if we save counter per 100 hits and reset

Thanks in advanced.

Kevin
  • 3
  • 2

3 Answers3

2

almost exactly what I do for banners as well, random sampling.

$freq_banners = array(
    5  => 'banner_3',
    10 => 'banner_1',
    85 => 'banner_2',
);
$use_banner = null;
$sum = 0;
$key = rand(1,100);
foreach ( $freq_banners as $banner_freq => $banner ) {
    $sum += $banner_freq;
    if ( $key <= $sum ) {
        $use_banner = $banner;
        break;
    }
}

Cheers

smassey
  • 5,875
  • 24
  • 37
1

You don't need to know about how many visitors. The only thing you need to do is take a random number between 1 and 100, and if it is 70 or lower, it is within this 70% range.

Eventually this will work out, and display the banner to 70% of the people:

if (rand(1,100) <= 70) {
    display_banner();
}

If you want to keep this number, and show it to the user for all page views, then store it in a $_SESSION var of some sort, and based on that value display the banner.

Rene Pot
  • 24,681
  • 7
  • 68
  • 92
  • I think you want to use `<=` here instead of `==`? Otherwise it would just be 1% :) – Nanne Apr 06 '12 at 10:26
  • It will show only to the 70th percentile... if(rand(1,100)<=70) is the correct test – Paolo Stefan Apr 06 '12 at 10:27
  • i think it relatives to use random.. and how about rand() performance? i will update the question to save the visitor hits thanks for the comment – Kevin Apr 06 '12 at 10:29
  • @Topener thanks for the answer.. and i see it's better to use mt_rand that claimed is 4x faster than rand and give more precise random http://stackoverflow.com/questions/7808021/whats-the-disadvantage-of-mt-rand – Kevin Apr 07 '12 at 00:36
0

I believe

$percentageVisitors  =  ceil(($currentVisitors / $totalVisitors) * 100) ;

Solution

if( $percentageVisitors >= 70)
 {
    showRandomAdvert();
 }

I hope this helps

Than

Baba
  • 94,024
  • 28
  • 166
  • 217