Chapter 4 Exercises
Exercise 6: Creating Random Numbers
The last function you will learn about in this chapter is rand(), a random-number generator:
The rand() function can also take minimum and maximum parameters, if you prefer to limit the generated number to a specific range:
These values are inclusive, so in this case 0 and 10 are feasible returned values.
In this exercise you will create a simple Lucky Numbers script utilizing random number generation.
Note: A number of Helpful Tips are located at the end of this web page for reference as you complete this exercise. There is also an Advanced Topic for additional learning.
Generate random numbers:
Script 4-6: The rand() function generates random numbers.
- Create a new document in your editor with the title Lucky Numbers:
- Include the PHP tags, and address error management, if necessary:
- Create three random numbers:
This script prints out a person’s lucky numbers, much like those listed on the back of the fortune found within a fortune cookie. These numbers are generated by calling the rand() function three separate times and assigning each result to a variable. - Print out the numbers:
The print() statement is fairly simple. The numbers are printed with tabs between them. By placing the tab-separated numbers in the HTML <pre> tags, you put some space between the printed numbers in the web browser. The <pre> tags tell the browser to abide by the existing formatting, which in this case, means the browser should honour the tabs. (Web browsers normally ignore tabs.) - Close the PHP code and the HTML page:
- Save your script as random.php to your XAMPP folder (c:\XAMPP\htdocs\202\chapter4).
- Using Cyberduck, upload the file to the production server, and test it in your browser, making sure you are looking at the production server version of the file. (Figures 4-11 and 4-12). Simply refresh your browser to produce different results every time.
Figure 4-11: The rand() function generates random numbers.
Figure 4-12: Running the script again produces different results.
- The getrandmax() function returns the largest possible random number that can be created using rand(). This value differs by operating system.
- PHP has a second function that generates random numbers: mt_rand(). It works similarly to (but, arguably, better than) rand() and is the smarter choice for sensitive situations like cryptography.