Interesting Code Question

By | December 16, 2008

Over in the osCommerce forum, Stephan asked;

Take gflash01.gif gflash02.gif gflash03.gif … gflash10.gif

Then line up the 10 pics next to each other with a 5px space between them and make the website dispay them in a random order. They are white flash/fading gifs with the same name but different flash/fade times. My goal is to create a random patter emerging for each person who visits my site.

Think of it as a footer on a music composing website that helps people composing songs to get ideas from emerging patterns.

I actually have done something very similar to this on a previous project, however my previous project was text files (in a list) rather than gif files side by side. So it was easy for me to supply the code, however as I did not read the question properly, my first code suggestion was as follows:


What this does is find all the filenames that start with “gflash” and end in “.gif” and print them off as images. What’s wrong about this? It won’t work in random order. Another forum user came up with a solution based off the above code – which works, but uses more code than is necessary.

So I then came up with:


This looks very similar to the previous code, but introduces a couple of new elements. For starters I use the “shuffle” to randomise the order of the array of images, then use a loop to print them out.

Deconstructing the code

[php]$filename = glob(“gflash*.gif”);[/php]

The “glob” finds all the filenames that start with “gflash” and end in “.gif” and puts those filenames into an Array called $filename.


Pretty obvious! This randomises (or shuffles) the contents of the Array.

[php]for ($i = 0; $i <= 9; $i++) { echo '‘;

Use a for loop to iterate through the Array, printing out the HTML to show each image. I use $i as the count, and so the $filename[$i] will show each entry in the Array.

Sounds more complicated than it really is, I think.

One thought on “Interesting Code Question

  1. enigma1

    nice, you could also add an extra validation step in case no images are present and the glob function returns false,

    if( is_array($filename) ) {
    // of code…

Leave a Reply

Your email address will not be published.