Rotating banner using PHP array shuffle or array_rand

Posted under » PHP on 26 March 2014

There was a time where rotating banner would mean a random ad banner appearing based on weightage. Not the kind where there is like a slideshow going on. This is because a spot could be shared with a few banners and if the sites got 500 hits, 250 would go to banner A and 250 to B. A simple way to do this is to put the 2 banner as arrays and then randomnize it. If you want it to be exactly 50% 50% then you have to have a count which I won't do for this example.

Using array_rand

$banner2 = array(
   1 => array('url' => 'http://yahoo.com', 'img' => 'yahoo.png'),
   2 => array('url' => 'http://google.com', 'img' => 'google.png'),
  ); 

$ban2 = array_rand($banner2);

$ad2 = '<a href="'.$banner2[$ban2]['url'].'"><img src="/imgs/'.$banner2[$ban2]['img'].'" width="130" height="75" /></a>';

Using shuffle

$banner2 = array(
   1 => array('url' => 'http://yahoo.com', 'img' => 'yahoo.png'),
   2 => array('url' => 'http://google.com', 'img' => 'google.png'),
  ); 

$ban2 = shuffle($banner2);

$ad2 = '<a href="'.$banner2[$ban2]['url'].'"><img src="/imgs/'.$banner2[$ban2]['img'].'" width="130" height="75" /></a>';

print or echo ad2

See also the javascript version.
 

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data