Random Images

One way designers add variety to a website is to have a random image appear in the header of the page. A great way to implement this is using the mt_rand() function in php. This function takes two arguments (1 and 5 in the example below) and returns a random integer in the range specified by the two arguments.

Example: <?php $logoId = mt_rand(1,5);?>

Note: I’ve been informed that in php < 4.2.0, mt_rand() must be seeded manually. An easy way to do this is to add this line before your mt_rand() call.

<?php mt_srand((double) microtime() * 1000000); ?>

Once you have a variable ($logoId in this example) containing your random integer, you can use that in the file name specified by the source property of your image tag.

Example: <img src="/images/logo_v<?php echo $logoId;?>.jpg" alt="alt text"/>

In this example, if $logoId is 4 then the image source will be /images/logo_v4.jpg. Likewise, if $logoId is 2 then the images source will be /images/logo_v2.jpg. This is a very easy way to have a random image. Once you have those two lines of code, you just have to make sure your image files exist and you’re done. If you wanted to have six images instead of five, you would just change the 5 in mt_rand() to a 6 and add the appropriate image file to your images folder.

Posted by ryan on February 14, 2005

5 Responses to Random Images

  1. tidaugherty:

    Fun! Boo hoo Earthlink doesn’t support php on my personal site…but the DO on my webhosted site, so it took a while, but I FINALLY got a test page to work…

  2. tidaugherty:

    And now I know NOT to include the greater than/less than symbols surrounding code when posting comments.

  3. tidaugherty:

    Question: How do you force line breaks and paragraph breaks within comments? BR didn’t work but maybe P, or P then BR will - I’ll try it now.

  4. tidaugherty:

    Well…maybe 1 more post, because the P worked! but I forgot to remove the less than/greater than symbols when I pasted the code, so just one more post tonight - PROMISE!!!

  5. Ryan:

    It’s a little tricky to get code to display, you actually have to type