Banner Advert Rotation With PHP

5th May 2008 - 2 minutes read time

A normal procedure with banner adverts is to rotate them randomly, but also to display some more than others. Lets say that you had 3 banner adds and that you wanted to display them at different rates. To do this you can use the rand() function to generate a random number that can then be used to see what banner advert will be displayed.

First we generate the random number, in our case it is between 1 and 100.

$number = rand(1, 100);

You can then use this number to figure out what banner ad to display. Because the random number is between 1 and 100 it is basically a percentage. So you can create a simple if statement that will determine what banner should be displayed.

  1. if ($number <= 70) {
  2. // will display 70% of the time
  3. $banner = 'banner1';
  4. } elseif ($number <= 90) {
  5. // will display 20% of the time
  6. $banner = 'banner2';
  7. } elseif ($number <= 100) {
  8. // will display 10% of the time
  9. $banner = 'banner3';
  10. }

You can then feed this into an image tag or something similar to enable the banner to display.

<img src="<?php echo $banner;?>" alt="" />

 

Add new comment

The content of this field is kept private and will not be shown publicly.