Random things with PHP

Especially when it comes to advertising, random things can be quite usefull. Random ads, sites, etc, can all be done with PHP very easily.

Step 1: Build an Array
You’ll first need an array of whatever will be random. If you are doing images, then the URLs to all the images. If you are doing banners then you’d need to do the full link and image code. In this example I’m going to make a random image script.

$randomarray = array("image1.jpg","image3.jpg","cat.gif","freddy.png");

Step 2: Output the Random Pick
Next is the core of it. I’ll put the code down, and then explain it in depth for those who need more explaination. You can of course just play with the code (the best way to learn).

$img = $randomarray[mt_rand(0, count($randomarray)-1)];
Header("Location: $img");

Explaination:

$max = count($randomarray) - 1;
$randnumber = mt_rand(0, $max);
$img = $randomarray[$randnumber];

Because looking at the one liner can be confusing, I’ve broken it down into 3 lines so you can understand it. The gist of it is this:

Line 1: Get the maximum value you want the random number to be. In this case, it is the number of items in the array minus one. That is because PHP counts 0, 1, 2, 3 not 1 2 3 4 like we do. There are 4 items in the array, but if you had a random number between 0 and 4 picked, then $randomarray[4] would return nothing.

Line 2: This is the core of it, mt_rand takes two arguements: $min, $max. Just give it the minimum and maximum numbers to pick between.

Line 3: This just assigns the chosen image to $img for easier inserting into the Header() statement.

One thought on “Random things with PHP

Comments are closed.