How to Create Your Own Random Number Generator in PHP

Share this article

Computers cannot generate random numbers. A machine which works in ones and zeros is unable to magically invent its own stream of random data. However, computers can implement mathematical algorithms which produce pseudo-random numbers. They look like random numbers. They feel like random distributions. But they’re fake; the same sequence of digits is generated if you run the algorithm twice.

Planting Random Seeds

To increase the apparent randomness, most algorithms can be passed a seed — an initialization number for the random sequence. Passing the same seed twice will still generate the same set of random numbers but you can set the seed based on external input factors. The easiest option is the current time but it can be anything; the last keypress, a mouse movement, the temperature, the number of hours wasted on YouTube, or any other factor.

Random PHP Functions

PHP offers a number of random number functions. The main ones are:
  1. rand() and the more efficient mt_rand() function. Both return a random number between zero and getrandmax()/mt_getrandmax(). Alternatively, you can pass minimum and maximum parameters:

    
    // random number between 0 and 10 (inclusive)
    echo mt_rand(0, 10);
    
  2. srand($seed) and mt_srand($seed) to set a random number seed. This has been done automatically since PHP 4.2.0.

PHP is Too Random!

There are instances when creating a repeatable list of pseudo-random numbers is useful. It’s often used for security or verification purposes, e.g. encrypting a password before it’s transmitted or generating a hash code for a set of data. Unfortunately, PHP can be a little too
random. A generated sequence will depend on your hosting platform and version of PHP. In other words, you can’t guarantee the same ‘random’ sequence will be generated twice on two different machines even if the same seed is used.

Rolling Your Own Random Class

Fortunately, we can write our own random number generator. You’ll find many algorithms on the web, but this is one of the shortest and fastest. First, we initialize our class and a random seed variable:

class Random {

	// random seed
	private static $RSeed = 0;
Next we have a seed() function for setting a new seed value. For the algorithm to work correctly, the seed should always be a positive number greater than zero but not large enough to cause mathematical overflows. The seed function takes any value but converts it to a number between 1 and 9,999,999:

	// set seed
	public static function seed($s = 0) {
		self::$RSeed = abs(intval($s)) % 9999999 + 1;
		self::num();
	}
Finally, we have our num() function for generating a random number between $min and $max. If no seed has been set it’s initialized with PHP’s own random number generator:

	// generate random number
	public static function num($min = 0, $max = 9999999) {
		if (self::$RSeed == 0) self::seed(mt_rand());
		self::$RSeed = (self::$RSeed * 125) % 2796203;
		return self::$RSeed % ($max - $min + 1) + $min;
	}

}
We can now set a seed and output a sequence of numbers:

// set seed
Random::seed(42);

// echo 10 numbers between 1 and 100
for ($i = 0; $i < 10; $i++) {
	echo Random::num(1, 100) . '<br />';
}
If you’ve copied this code exactly, you should see the following values no matter what OS or version of PHP you’re running:
76
86
14
79
73
2
87
43
62
7
Admittedly, repeatable “random” numbers isn’t something you’ll need every day — you’re more likely to require something closer to real randomness and PHP’s functions will serve you better. But there may be occasions when you find this useful.

Frequently Asked Questions (FAQs) about PHP Random Number Generator

What is the difference between rand() and mt_rand() in PHP?

In PHP, both rand() and mt_rand() are used to generate random numbers. However, they differ in terms of speed and randomness. The mt_rand() function is faster and produces a better random value compared to the rand() function. This is because mt_rand() uses the Mersenne Twister algorithm, which is known for its speed and high-quality randomness. On the other hand, rand() uses the libc random number generator, which is slower and less random.

How can I generate a random number within a specific range in PHP?

In PHP, you can generate a random number within a specific range using the rand() or mt_rand() function. Both functions accept two parameters: the minimum and maximum range. For example, to generate a random number between 1 and 10, you would use rand(1, 10) or mt_rand(1, 10).

What is the purpose of the random_int() function in PHP?

The random_int() function in PHP is used to generate cryptographically secure pseudo-random integers. This means that the generated numbers are suitable for use where unbiased results are critical, such as in cryptography. Unlike rand() and mt_rand(), the random_int() function can generate a truly random number, making it more secure.

How can I generate a random string in PHP?

In PHP, you can generate a random string by combining the chr() function with the rand() or mt_rand() function inside a loop. The chr() function returns a specific character according to the ASCII value. By generating random ASCII values and converting them to characters, you can create a random string.

Why does my PHP script generate the same random number each time it runs?

If your PHP script generates the same random number each time it runs, it’s likely because you haven’t seeded the random number generator. Seeding is the process of providing an initial value to a random number generator. In PHP, you can seed the random number generator using the srand() or mt_srand() function.

How can I generate a random float in PHP?

In PHP, you can generate a random float by dividing a random integer by the maximum value of the random number generator. For example, to generate a random float between 0 and 1, you could use rand(0, getrandmax()) / getrandmax().

Is it possible to generate a random number without repetition in PHP?

In PHP, generating a random number without repetition can be achieved by storing previously generated numbers in an array and checking if the new number already exists in the array before using it.

How can I generate a random number with a specific number of digits in PHP?

In PHP, you can generate a random number with a specific number of digits by using the rand() or mt_rand() function with a range that matches the desired number of digits. For example, to generate a random number with 5 digits, you could use rand(10000, 99999) or mt_rand(10000, 99999).

What is the maximum value that can be generated by the rand() function in PHP?

In PHP, the maximum value that can be generated by the rand() function depends on the system. On a 32-bit system, the maximum value is typically 2147483647. On a 64-bit system, the maximum value is typically 9223372036854775807.

How can I generate a random alphanumeric string in PHP?

In PHP, you can generate a random alphanumeric string by creating a string that contains all the characters you want to include, and then selecting random characters from it. You can use the rand() or mt_rand() function to generate the random index.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

PHPrandom
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week