with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

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.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.