Random Numbers in PHP - Random Dice Roller
by terror on Jun.11, 2009, under Tutorials
This tutorial will take a brief look at using random numbers in PHP. I’ve used a dice rolling example to demonstrate how the rand() function can be used to select an image at random. This example can be implemented and used for other applications such as an ad rotation script.
PHP comes with a basic function called “rand()”. It can generate random numbers, depending on what parameters you set. For example:
<? //Print a random number between 5 and 15 (including 5 and 15) echo rand(5, 15); ?>
This will print a random number between 5 & 15, including 5 & 15.
Random Dice Roller
This demo illustrates how to use the rand() function to select random images each time the page loads.
Before we get started, here are the dice images I used (Right Click ->Save image as):
Once you have chosen your images, create an array, called “img”:
//Create an array for dice images $img = array();
Next step is to populate your array with mulitple image files:
//Populate array with dice images $img[] = '<img src="dice1.png" alt="" />'; $img[] = '<img src="dice2.png" alt="" />'; $img[] = '<img src="dice3.png" alt="" />'; $img[] = '<img src="dice4.png" alt="" />'; $img[] = '<img src="dice5.png" alt="" />'; $img[] = '<img src="dice6.png" alt="" />';
Note that im storing the HTML for the images in the array.
Now we have our array we need to count the total images stored inside it. Reason being, because we need to generate a random number between 1 & the number of images.
//Count images in array (-1 because we don't want to include 0 in the array) $max = count($img) - 1;
The final step is to generate a random number between 1 & the number of images, select the correct image and print it.
//Generate a random number between 1 &amp;amp;amp;amp; 6 - (max) $count = rand(0,$max); //Assign $dice with the image chosen in the array $dice = $img[$count]; //Print the dice image echo $dice;
In my example I have include the option to roll the dice again. This is simply a submit button that refreshes the page. By refreshing your page the images will randomly alternate.
The full souce code is shown below:
//Create an array for dice images $img = array(); //Populate array with dice images $img[] = '<img src="dice1.png" alt="" />'; $img[] = '<img src="dice2.png" alt="" />'; $img[] = '<img src="dice3.png" alt="" />'; $img[] = '<img src="dice4.png" alt="" />'; $img[] = '<img src="dice5.png" alt="" />'; $img[] = '<img src="dice6.png" alt="" />'; //Count images in array (-1 because we don't want to include 0 in the array) $max = count($img) - 1; //Generate a random number between 1 & 6 $count = rand(0,$max); //Assign $dice with the image chosen in the array $dice = $img[$count]; //Print the dice image echo $dice;
I hope this tutorial helps!







