PHP Tutorial – How To Display Random Ads

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.
PHP tutorial

  1. 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.
  2. 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";
     case 2:
     include "adiquity.php";
     case 3:
     include "buzzcity.php";
  3. 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.


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)];
Don’t miss out!
Subscribe to My Newsletter
Invalid email address