PHP Random Number Generator

by Vincy. Last modified on July 2nd, 2022.

In this article, we are going to see how to generate a random number using a set of predefined PHP functions. There are two prime functions to deal with random number generation. These are,

  • rand()
  • mt_rand()

rand() vs mt_rand()

  • These two functions might have two optional arguments for specifying the min and max limit for generating a random number.
  • If the min and max values are not specified, then the limits will be taken automatically, that is, 0 and the value returned by the getrandmax() or mt_getrandmax().
  • The value returned by getrandmax() function is somewhat limited depending on the platform we are working on. In such cases, mt_getrandmax() is used to pick maximum limit for mt_rand() function.
  • mt_rand() is comparatively quicker than rand() function.
  • Seed for the random number generators, rand() and mt_rand() can be provided by srand() and mt_srand() functions respectively

Seeding PHP Random Number generator

PHP has set of functions like srand() and mt_srand() to seed random number generators. Seeding is nothing but sending an integer as an argument of srand() or mt_srand(). Since the random numbers are created based on this integer, we need to call srand() or mt_srand() before calling rand() and mt_rand().

Importantly, the number to be sent as seed should be changed randomly. If we pass the same seed every time, then the same random number will be created for all attempts.

After PHP version 4, seeding is optional. Without a seeding, PHP rand() and mt_rand() will automatically get such a random integer for creating random numbers.

Example: PHP Random Number Generator

The following PHP code will print random numbers to the browser-based on the functions used. The first two lines are used for the seeding process. Random numbers will also be generated, without these two lines. The time() function is used to create a unique number for seeding at the time of execution.

echo rand() . "<br>";
echo mt_rand() . "<br>";
echo rand(20, 1000) . "<br>";
echo mt_rand(1, 10) . "<br>";
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page