Web Design Tutorials Made Easy


Ad / image Rotation using array |

In many sites, there is the need for some form of ad rotation…

Serving dynamic content to visitors is great for keeping your site fresh, and this example can be applied to any purpose. Using only “arrays”, it cuts out the need for a database.

So let’s get going.


Some prior knowledge of arrays is required, but it’s not too hard. We will be building a function to grab a random array values and build a link and print it. Simple.

Firstly we will look at our array values…

$link[0]['image'] = '/images/advert.jpg';
 
$link[0]['url'] = 'http://www.focusedtutorials.com';
 
$link[0]['desc'] = 'This is a test description';

We know our array is called $link. The first square bracket is our identifier, “[0]”. To add other links, we will increment this value – “[1] , [2] , [3]” etc. The second block is our value – in our case [‘image’] is the path to the image…

So hopefully, we will end up with a few entries in our array…

$link[0]['image'] = '/images/f_t_image.jpg';
 
$link[0]['url'] = 'http://www.focusedtutorials.com';
 
$link[0]['desc'] = 'focusedtutorials.com';
 
$link[1]['image'] = '/images/webradiance.png';
 
$link[1]['url'] = 'http://www.webradiance.com';
 
$link[1]['desc'] = 'Web Development forum';
 
$link[2]['image'] = '/images/affilate.jpg';
 
$link[2]['url'] = 'http://www.some-affiliate.com';
 
$link[2]['desc'] = 'This is a test description';

Its ok having this array with our links in, but we need to select a random entry from the array. To do this we will use the PHP function RND_ARRAY. This will allow us to pick one or more random entries out of an array. We only want the one though.

$random = array_rand($link);

We add our array into array_rand, basicly it finds a random entry in the array $link.We will call the random number $random.

To call our array entry normally we would type:


echo $link[1][ 'url'];

Where we specified we wanted entry one ( see the [1] bit) however, we want to change that for our random number.

So!


echo $link[$random]['url'];

Now we will get the ‘url’ value from a random entry in our array.

Use this method for the rest of the values, to build our link.
echo "<a href='".$link[$random]['url']."'><img src='".$link[$random]['image']."' alt='".$link[$random]['desc']."'/></a>";
Throw this in a function and HOORAY! We can call thos function when we wish! Download the source file to see it in action!

Source file for the ad roation using arrays

No Responses to 'Ad / image Rotation using array'

Be the first to comment on this post!

Leave a Reply

*required

*required / not published

Categories
Archives