Random Numbers in PHP

Here’s the translation of the Go code example to PHP, formatted in Markdown suitable for Hugo:

PHP’s mt_rand() and mt_getrandmax() functions provide pseudorandom number generation.

<?php

// For example, mt_rand(0, 99) returns a random integer n,
// 0 <= n <= 99.
echo mt_rand(0, 99) . ",";
echo mt_rand(0, 99) . "\n";

// mt_rand() / mt_getrandmax() returns a float f,
// 0.0 <= f < 1.0.
echo mt_rand() / mt_getrandmax() . "\n";

// This can be used to generate random floats in
// other ranges, for example 5.0 <= f' < 10.0.
echo (mt_rand() / mt_getrandmax() * 5) + 5 . ",";
echo (mt_rand() / mt_getrandmax() * 5) + 5 . "\n";

// If you want a known seed, use mt_srand() to set
// the seed for the Mersenne Twister generator.
mt_srand(42);
echo mt_rand(0, 99) . ",";
echo mt_rand(0, 99) . "\n";

// Using the same seed will produce the same sequence
// of random numbers.
mt_srand(42);
echo mt_rand(0, 99) . ",";
echo mt_rand(0, 99) . "\n";

Some of the generated numbers may be different when you run the sample.

$ php random-numbers.php
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

See the PHP manual for references on other random quantities that PHP can provide.

In PHP, we use the Mersenne Twister algorithm for generating random numbers, which is considered to be a good pseudorandom number generator. The mt_rand() function is generally preferred over the older rand() function for its better statistical properties.

Note that for cryptographically secure random numbers, you should use the random_int(), random_bytes(), or openssl_random_pseudo_bytes() functions instead.