Basic Image/Ad Rotation Script

Rotation scripts can come in handy for many things — multiple decorational images for your website, photograph rotational scripts, banner advert rotations and more. This basic script will provide a quick ‘no frills’ rotation method which can be placed anywhere on a PHP-enabled website.

First, we need to ‘open’ PHP and declare the array which will hold the images or text that we want to rotate, like so:

<?php
$img = array();

?>

Next we need to assign our ‘stuff’ to our array — this can be images, banners, or text — for my example I’m using images. Each item needs to be added to our array like so:

$img[] = '<img src="image-1.gif" alt="" />';
$img[] = '<img src="image-2.gif" alt="" />';
$img[] = '<img src="image-3.gif" alt="" />';

We now need to count the amount of things in our array, and generate a random number, not exceeding the amount of items and no smaller than 0 (because arrays start at 0 by default):

$max = count($img) - 1;
$count = rand(0,$max);

Last but not least, we need to echo one item from our array to the browser, using our random number to ‘choose’ which item to display, putting the entire snippet together and creating our rotation script:

<?php
$img = array();

$img[] = '<img src="image-1.gif" alt="" />';
$img[] = '<img src="image-2.gif" alt="" />';
$img[] = '<img src="image-3.gif" alt="" />';

$max = count($img) - 1;
$count = rand(0,$max);

echo $img[$count];
?>

Note: if you add text to your array, make sure you escape any apostrophes with a backslash, like so:
$img[] = 'I'm escaping any additional apostrophes!';
And if you want to link to a website, you’d do so like so:
$img[] = '<a href="http://www.a.com"><img src="image-1.gif" alt="" /></a>';

Comments

  1. I think the example that says to escape apostrophes is missing its backlash. Would be ‘I\’m escaping any additional apostrophes!’ right?

Speak Your Mind

*