Blog

Tutorial: Easiest way to display random image using PHP

First of all, this tutorial is mainly for the beginners who start learning programming especially PHP. If you are building some website and sometimes, you might need to display a random image per page load. It that case, you could use this method. There might be some other ways to achieve this but I find that this is the easiest way at least, for me.

<?php
$iArr = array(‘image1.jpg’, ‘image2.jpg’, ‘image3.jpg’);
$no = sizeof($iArr)-1;
$random = mt_rand(0, $no);
$path = ‘images/’;
$ranImg = $iArr[$random];
$img = $path.$ranImg;
echo $img;
echo ‘<img src=”‘.$img.’” alt=”"/>’;
?>

<?php

$iArr = array(‘image1.jpg’, ‘image2.jpg’, ‘image3.jpg’); //create an array of image

$no = sizeof($iArr)-1;

$random = mt_rand(0, $no); //get random number between 0 and array size

$path = ‘images/’; //this is the path to your images

$ranImg = $iArr[$random]; //get random image from array

$img = $path.$ranImg; //the full image path e.g. images/image1.jpg

echo ‘<img src=”‘.$img.’” alt=”"/>’; //display the random image

?>

I believe the code is quite simple and self explained. Please feel free to share your thoughts in comments.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • LinkedIn
  • Twitter

Do you like this article?

30.07.2010 | 0 Comment
php, tutorial

Leave a Reply

(required)

(required)