Use Random Extension in PHP 8.2

Use Random Extension in PHP 8.2

Since PHP 8.2, we can use a new extension named Random for generating random numbers via object-oriented way. Random extension is a part of the PHP core and there is no additional installation needed.

Existing random number functions (e.g. random_bytes, random_int, etc.) has been moved to the Random extension. All of these functions continue to be in the global namespace and the functionality of the functions has not changed. There are no compatibility issues in applications.

Random extension provides a new Random\Randomizer class. It allows generating random bytes and integers, randomize string and array elements, and randomly select array keys.

<?php

use Random\Randomizer;

$rnd = new Randomizer();

echo bin2hex($rnd->getBytes(8)).PHP_EOL;    // Random 8 bytes
echo $rnd->nextInt().PHP_EOL;               // Random integer
echo $rnd->getInt(0, 10).PHP_EOL;           // Random integer [0, 10]
echo $rnd->shuffleBytes('hello').PHP_EOL;   // Randomize string
print_r($rnd->shuffleArray([3, 5, 7]));     // Randomize array elements
print_r($rnd->pickArrayKeys([3, 5, 7], 2)); // Randomly select 2 array keys

The constructor of the Random\Randomizer class accepts an instance of the class that implements the Random\Engine interface. It can be implemented by a class which provides Pseudo Random Number Generator (PRNG) functionality.

There is the Random\CryptoSafeEngine interface that extends Random\Engine interface for classes that provides cryptographically secure PRNG (CSPRNG) implementation.

Random extension provides the following PRNG implementations:

<?php

use Random\Engine\Mt19937;
use Random\Engine\PcgOneseq128XslRr64;
use Random\Engine\Secure;
use Random\Engine\Xoshiro256StarStar;
use Random\Randomizer;

$rnd = new Randomizer(new Mt19937());
echo $rnd->nextInt().PHP_EOL;

$rnd = new Randomizer(new PcgOneseq128XslRr64());
echo $rnd->nextInt().PHP_EOL;

$rnd = new Randomizer(new Xoshiro256StarStar());
echo $rnd->nextInt().PHP_EOL;

$rnd = new Randomizer(new Secure());
echo $rnd->nextInt().PHP_EOL;

$rnd = new Randomizer(); // Random\Engine\Secure is used by default
echo $rnd->nextInt().PHP_EOL;

Leave a Comment

Cancel reply

Your email address will not be published.