skip to Main Content

Update – this question applies to PHP < 8.2 – for 8.2+, You have access to Randomizer


PHP supports `mt_rand()` and `mt_srand()`, but these are global and static.

I notice in the PHP C source that mt_rand uses a engine_mt19937 instance; is there a way in PHP to instantiate our own instance of this RNG so we can control its seed?

2

Answers


  1. is there a way in PHP to instantiate our own instance of this RNG so we can control its seed?

    With PHP 8.2+, yes. See the Random classes. You can do something like:

    $rand1 = new RandomEngineMt19937($seed1);
    $value1 = $rand1->generate();
    
    $rand2 = new RandomEngineMt19937($seed2);
    $value2 = $rand2->generate();
    
    Login or Signup to reply.
  2. On PHP 8.2+, yes. See @AlexHowansky’s answer for that. On earlier PHP versions, no.

    Your link to the source code points to the master branch, which already has the PHP 8.2 logic in it since it was officially released last month. That is why the master branch includes the reference to an MT19937 engine.

    On older versions (e.g. the latest 8.1 branch) you can see that mt_rand() did not use a configurable engine but just checked if it was already seeded. PHP 8.1 and earlier used a single global generator for mt_rand() so it is not possible to have multiple RNGs with different seeds if you want to use the native functions.

    Having said that, you could probably roll your own implementation of an MT19937 RNG for PHP 8.1. Others have.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search