Rotate Ads with PHP

Written by Mark Sanborn: May 23, 2008

There comes a point where a site can have too many advertisements or there simply isn’t enough space for another ad. We also don’t want to distract our users from the content too much. This is where ad rotating can come in handy. With rotating you can have two ads displayed in the same space.

Split testing is another great reason for rotating ads. If you remember back to my post about split testing Adsense ads I found there was a significant difference between different the 250x250 block and the 300x250 block. These results came as a shock to me. Maybe your ads will surprise you you. The only way you will know is to test them yourself since all sites will have varying results.

The code

<?php $splitIt = rand()&1; echo "<!-- $splitIt -->"; ?>
<?php if ($splitIt == 0) { ?>
<!-- First ad goes here -->
<?php } ?>

<?php if ($splitIt == 1) { ?>
<!-- Second ad goes here -->
<?php } ?>

Although it is best to to use only two ads when testing, we can add multiple advertisements for rotation purposes by using this code:

<?php $splitIt = rand()&3; echo "<!-- $splitIt -->"; ?>
<?php if ($splitIt == 0) { ?>
<!-- First ad goes here -->
<?php } ?>

<?php if ($splitIt == 2) { ?>
<!-- Second ad goes here -->
<?php } ?>

<?php if ($splitIt == 3) { ?>
<!-- Third ad goes here -->
<?php } ?>

Bonus Tip

If you noticed in these examples that I didn’t use:

$splitIt = rand(0,1);
$splitIt = rand(0,3);

This is because it is faster to use bitwise operations instead of math calculations; however it only works for ranges that aren’t a power of two. For example you could use the bitwise method for 1, 3, 5, 7 but not 2 or 4.

To rotate between 4 ads you would need to use:

$splitIt = rand(0,4);

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Share: