Over the weekend, i was writing a PHP wapsite and i wanted to display random advert at the footer of the site, so i wrote a PHP code snippet to achieve this. follow the steps below to learn how i did it.
- Say we want to randomly display Google adsense, Adiquity and buzzcity, firstly create three PHP files “adsense.php” “adiquity.php” and “buzzcity.php” with their respective adcode saved in it.
- We are going to use PHP include function to include the ads and switch function to randomly display the Ads as shown below.
<? //Chooses a random number $num = Rand (1,3); //Based on the random number, gives a quote switch ($num) { case 1: include "adsense.php"; break; case 2: include "adiquity.php"; break; case 3: include "buzzcity.php"; break; } ?>
- To alter the number of Ads to display, change “3” in the code above to the number of Ads to randomly display and also add a corresponding case value.
Update
For faster and less code use the script below.thanks to Stewart Souter
<?php $theAds = array('adsense.php', 'adiquity.php', 'buzzcity.php');
include $theAds[mt_rand(0, count($theAds) - 1)];
?>