PHP Tutorials

Random Text/Images

This tutorial walks you through how to create a random image appear or some random text...
I know many people want to have some sort of randomisation to their web site. You may want to have random banners, title, links, whatever. In this tutorial, I will show you how to generate random things of your preference.

If we want to have random things it will be easiest to make an array. So we start out with making an array called $Data and fill it with 10 things. You can add or subtract as many entries as you like.

$Data[1] = "Banner1";
$Data[2] = "Banner2";
$Data[3] = "Banner3";
$Data[4] = "Banner4";
$Data[5] = "Banner5";
$Data[6] = "Banner6";
$Data[7] = "Banner7";
$Data[8] = "Banner8";
$Data[9] = "Banner9";
$Data[10] = "Banner10";
Now that we have all the Data that we need, we need to randomise. To do this, we need to get a random number. The number cannot be less then the number of the first element in the array, (1) or be larger than the last element. So we want a random number 1 - 10. What happens if is 3.432324? This might generate an error. We can round down. We will want to floor() the random number.
$i = rand(1, size of($Data));
Now that we have the random number, we will want to use that as the index value to call the element in the array.
echo $Data[$i];
Your done! All you have to do is put in the information you want into the values for each element in the array. To use it in a page, save the file, and include it in the page, Like this:
Note that to include the file in the page, you will have to save the page, where the random generator is as a php file or phtml file for it work. If you Enjoyed this tutorial let me know, send any comments to my at or talk to me on by username is Adman.
This tutorial was by Adman, brought to you by Robouk, please post any questions in the forum. Thank you.