i am dustin diaz

and while you're at it...

boosh.

don't worry about it.

A Simple PHP image rotator

Thursday, December 9th, 2004

This has probably been done a thousand times over by many programmers, but I thought I’d offer just one more to the collection.

Three Simple Steps

PHP: Function randomImage

<?php
function randomImage ( $array ) {
  $total = count($array);
  $call = rand(0,$total-1);
  return $array[$call];
}
?>

The Image Array

<?php
$my_images = array (
  "dustin.jpg",
  "Jeffrey.jpeg",
  "Chrissy.png",
  "Kristen.gif"
);
?>

The embedded PHP into your XHTML:

<?php
echo '<img
  src="'.randomImage($my_images).'"
  alt="Random Image" />';
?>

Why did I bother writing this? Because I’ve seen way too many scripts and downloads and all that yada yada just to make some simple random image rotator.

If you want to add more images, just put in an extra item into the array.

Case closed.

7 Responses to “A Simple PHP image rotator”

  1. pxl

    I always wondered how to do that……
    lol.

  2. GL

    I need to know how to make like a mini slide show that automatically flips through images in a folder. I mean live, like in intervals.

  3. cchill

    The problem with this code is that the random function will often pick the same pic from the array 2 or 3 times in a row before choosing a different pick.

  4. Quirky

    And how to to a non-random rotator, meaning: starting from the first in line and when reaching the alst in the array, restarting again. and maybe a setTimeOut

  5. GreyFox

    Great job. I bookmarked this a while ago and I figured I should comment.

  6. Overdryve

    How about doing it with a folder with tons of images??

  7. Arthur Thompson

    I have just started with doing PHP and your code looks interesting to try for a resolvig of a problem i’ve.

find it

recent

me on twitter

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @Twitter, author of JavaScript Design Patterns, and a photographer. This is my website. Welcome!

On this site I write about JavaScript. I appreciate you dropping by.