Creating a Random Number

Creating a Random Number

The dice game, like many other games, relies on random number generation to make things interesting. Most languages have at least one way to create random numbers. PHP makes it very easy to create random numbers with the rand function.

Viewing the "Roll 'em" Program

The roll' em program shown in Figure 3.2 demonstrates how the rand function can be used to generate virtual dice.

Click To expand
Figure 3.2: The die roll is randomly generated by PHP.

The code for the rollEm program shows how easy random number generation is.

<title>Roll Em!</title>
<h1>Roll Em!</h1>
<h3>Demonstrates rolling a die</h3>

$roll = rand(1,6);
print "You rolled a $roll";
print "<br>";
print "<img src = die$roll.jpg>";
Refresh this page in the browser to roll another die.


I used the rand function to generate a random number between one and six (inclusive) and stored the resulting value in the $roll variable. The rand function expects two parameters. The first value is the lowest number you wish, and the second value represents the highest number. Since I want to replicate an ordinary six-sided die, I told the rand function to return a value between one and six. Since I knew that rand would return a value, I assigned that resulting value to the variable $roll. By the time the line

$roll = rand(1,6);

has finished executing, the $roll variable will have a random value in it. The lowest possible value will be one, the highest possible value will be six, and the value will not have a decimal part. (In other words, it will never be 1.5.)


If you're coming from another programming language, you might be a little surprised at the way random numbers are generated in PHP. Most languages allow you to create a random floating point value between zero and one, and then require you to transform that value to whatever range you wish. PHP allows (in fact requires) you to create random integers within a range, which is usually what you want anyway. If you really want a value between zero and one, you can generate a random number between zero and 1000 and then divide that value by 1000.

Printing a Corresponding Image

Notice the sneaky way I used variable interpolation. I carefully named my first image die1.jpg, the second die2.jpg, and so on. When I was ready to print an image to the screen, I used an ordinary HTML image tag, but the source is set to die$roll.jpg. If $roll is three, the image will show die3.jpg. You'll see some other ways to let the computer respond to random numbers shortly, but variable interpolation can be a wonderful trick if you know how the file names are structured.


You might recall from Chapter 2, "Using Variables and Input" that interpolationis the technique that allows you to embed a variable in a quoted string by simply using its name.