Randomly Selecting Images with PHP

2009-09-07 19:17:18
Have you ever seen an image on a web page and wondered how it is randomly replaced with a different one when you click "reload" in your web browser?

This is a neat little trick that can be done in PHP and it is so easy. This article will explain how to do it.

First of all, you will need to write the PHP part of the code, which will randomly select the image. After that, you will place the PHP variable into the HTML.

<?
$image_array = array("images/1.jpg", "images/2.jpg", "images/3.jpg"); /* the paths of the images - to add extra paths, just follow the existing pattern: encased in quotes and separated by a comma */
$selection = $image_array[array_rand($image_array)]; /*this is the random choice of array value*/

$random_image = "<img src='".$selection."' />";
?>


Once that is done, you will need to add the variable $random_image into the page, like so:

<html>
<body>
<? echo $random_image; ?>
</body>
</html>


Once you have used this code, try a few page refreshes. You should see that it displays a random image from the selections.