gmp_random_seed()

When generating random or pseudo-random values, an initialisation vector – called seed – is commonly used to set up the generator. With PHP 7, you can now set your own seed for gmp_random(), gmp_random_bits(), and gmp_random_range() – the three functions for random number generation provided by the GMP extension – using gmp_random_seed().

This can be very handy when writing tests, for instance, as this allows for predicting the values generated. The sequence is completely determined by the given seed, thus reinitializing the generator with the same seed is going to always reproduce the exact same sequence of values.

The value passed to gmp_random_seed() needs to be either an integer, a string that can be interpreted as an integer, or a GMP number object that can be created using gmp_init() like so:

gmp_random_seed(100);
var_dump(gmp_strval(gmp_random(1)));

gmp_random_seed("100");
var_dump(gmp_strval(gmp_random(1)));

gmp_random_seed(gmp_init(100));
var_dump(gmp_strval(gmp_random(1)));

For the above example to work, the GMP extension needs to be installed. As all seed values in the given example translate to the same number and on top of that are static, when executed you should see the same “random” number all the time:

string(19) "7842303329126688544"
string(19) "7842303329126688544"
string(19) "7842303329126688544"

Be aware that even with a dynamic seed value, these functions are not designed for cryptography use cases. Cryptographically secure alternatives are, for instance, provided by means of random_bytes() and openssl_pseduo_random_bytes().