Generate a random image using Javascript or PHP

By generating random images you can display a unique page to each of your visitors instead of showing them all the same thing. To display randomly generated images, you need to know how to generate random numbers and work with those numbers.

Random image generation algorithm

You can use the following algorithm for generating random images. Examples using the algorithm with Javascript and PHP can be found below.

  1. Create an array with each item in the array being the name of an image.
  2. Declare a variable which will take the value of a randomly generated number from 0 (because arrays start at 0) to the length of the array of the images - 1. So in an array with 5 images, the variable will take the value of a randomly generated number between 0 and 4.
  3. Display the image from the images array at the index that matches the random number. So if the random number generated is 2, we will display the image at index 2. If the random number generated is 4, we will display the image at index 4, and so on.

Javascript

<script type="text/javascript"> //create an array of images var images = new Array("sky.jpg", "swan.jpg", "tree.jpg","waterfall.jpg", "apple.jpg"); //get the length of images array //and a random number between 0 and the length var length = images.length; var which = Math.round(Math.random()*(length-1)); //get the image at the index that matches the random number document.write('<img src="'+images[which]+'" />'); </script>
Output:

PHP

<?php //create an array of images $images = array("sky.jpg", "swan.jpg", "tree.jpg", "waterfall.jpg", "apple.jpg"); //get the length of images array //and a random number between 0 and the length $length = images.length(); $which = Math.round(Math.random()*(length-1)); //get the image at the index that matches the random number echo "<img src=\"$images[$which]\" />"; ?>
Output:

Every time you reload this page new images will appear for both examples. Try it out!

© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information