Banner Advert Rotation With PHP

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.

if ($number <= 70) {
 // will display 70% of the time
 $banner = 'banner1';
} elseif ($number <= 90) {
  // will display 20% of the time
 $banner = 'banner2';
} elseif ($number <= 100) {
 // will display 10% of the time
 $banner = 'banner3';
}

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

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

 

Comments

thanks

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 13 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.