Tuesday, July 27, 2010

Really Simple Random Image Using PHP

A popular effect on many websites is a random image that appears every time a page is reloaded. A recent project of mine required this effect on the homepage of the website, so I developed this really simple script using PHP.
Begin by placing the following code at the top of your page:
$image_array[0] = "image1.jpg";
$image_array[1] = "image2.jpg";
$image_array[2] = "image3.jpg";
$image_array[3] = "image4.jpg";
$image_array[4] = "image5.jpg";

$random = rand(0, count($image_array) - 1);

In the code above, I am assigning the image names I want to cycle through to an array. Next, I assign a variable to be my random number in the range zero to the last index in my array.

Now, go to the area in your HTML code where your images should be and make the image tag look as follows:
<img src="_images/<?php echo($image_array[$random]); ?>">
This should be pretty easy to understand; I'm simply filling the source attribute of the image tag with one of the names of the images from the array indexed by the random number I generated earlier in my code.

Like I mentioned earlier, this is a very simple script, but it achieves the result! To see this script in action, visit The Royal Closet website and refresh the homepage a couple times.