Creating Random Numbers
The last function you’ll learn about in this chapter is mt_rand(), a random-number generator. All it does is output a random number:
$n = mt_rand(); // 31 $n = mt_rand(); // 87
The mt_rand() function can also take minimum and maximum parameters, if you prefer to limit the generated number to a specific range:
$n = mt_rand(0, 10);
These values are inclusive, so in this case 0 and 10 are feasible returned values.
As an example of generating random numbers, let’s create a simple “Lucky Numbers” script.
To generate random numbers:
Begin a new document in your text editor or IDE, to be named random.php (Script 4.6):
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Lucky Numbers</title> </head> <body>
Script 4.6 The rand() function generates a random number.
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Lucky Numbers</title> 6 </head> 7 <body> 8 <?php // Script 4.6 - random.php 9 /* This script generates 3 random numbers. */ 10 11 // Address error handling, if you want. 12 13 // Create three random numbers: 14 $n1 = mt_and(1, 99); 15 $n2 = mt_rand(1, 99); 16 $n3 = mt_rand(1, 99); 17 18 // Print out the numbers: 19 print "<p>Your lucky numbers are:<br> 20 $n1<br> 21 $n2<br> 22 $n3</p>"; 23 24 ?> 25 </body> 26 </html>
Include the PHP tag and address error management, if you need to:
<?php // Script 4.6 - random.php
Create three random numbers:
$n1 = mt_rand(1, 99); $n2 = mt_rand(1, 99); $n3 = mt_rand(1, 99);
This script prints out a person’s lucky numbers, like those found on the back of a fortune cookie. These numbers are generated by calling the mt_rand() function three separate times and assigning each result to a different variable.
Print out the numbers:
print "<p>Your lucky numbers are:<br> $n1<br> $n2<br> $n3</p>";
The print statement is fairly simple. The numbers are printed, each on its own line, by using the HTML break tag.
Close the PHP code and the HTML page:
?> </body> </html>
Save the file as random.php, place it in the proper directory for your PHP-enabled server, and test it in your browser . Refresh the page to see different numbers .