Publishers of technology books, eBooks, and videos for creative people

Home > Articles

Using Numbers

  • Print
  • + Share This
This chapter is from the book

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:

  1. Begin a new document in your text editor or IDE, to be named random.php (Script 4.6):

    <!doctype html>
    <html lang="en">
      <meta charset="utf-8">
      <title>Lucky Numbers</title>

    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. */
    11  // Address error handling, if you want.
    13  // Create three random numbers:
    14  $n1 = mt_and(1, 99);
    15  $n2 = mt_rand(1, 99);
    16  $n3 = mt_rand(1, 99);
    18  // Print out the numbers:
    19  print "<p>Your lucky numbers are:<br>
    20  $n1<br>
    21  $n2<br>
    22  $n3</p>";
    24  ?>
    25  </body>
    26  </html>
  2. Include the PHP tag and address error management, if you need to:

    <?php // Script 4.6 - random.php
  3. 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.

  4. Print out the numbers:

    print "<p>Your lucky numbers

    The print statement is fairly simple. The numbers are printed, each on its own line, by using the HTML break tag.

  5. Close the PHP code and the HTML page:

  6. Save the file as random.php, place it in the proper directory for your PHP-enabled server, and test it in your browser a.jpg. Refresh the page to see different numbers b.jpg.


Click to view larger image

a.jpg The three random numbers created by invoking the mt_rand() function.


Click to view larger image

b.jpg Running the script again produces different results.

  • + Share This
  • 🔖 Save To Your Account