PHP 8.3: Random extension: New \Random\Randomizer::getBytesFromString method

Version8.3
TypeNew Feature

The \Random\Randomizer class in PHP 8.3 supports a new getBytesFromString method that returns a random number sequence of a requested length ($length parameter), only containing a bytes from the requested series of bytes ($string parameter).

Note that the \Random\Randomizer::getBytesFromString() method works on the byte level. It cannot effectively shuffle multi-byte characters such as Emojis, CJK characters, and Eastern/Indo characters.

\Random\Randomizer::getBytesFromString() method synopsis

namespace Random;  

class Randomizer {  
  // ...  

  /**  
   * @param string $string String of bytes/characters that will be used to return random bytes  
   * @param int $length Number of bytes in the return value.  
   * @return string  
   * 
   * @throws \ValueError if $string is empty  
   * @throws \ValueError if the $length is <= 0  
   * @throws \Random\BrokenRandomEngineError if the engine failed to generate random byte sequence in requested length.
   */
   public function getBytesFromString(string $string, int $length): string {  
   }
 }
  • Duplicate characters are allowed in the $string parameter. Multiple occurrences increase the probability of the particular character appearing in the returned randomized value.
  • Throws a \ValueError exception if the $string parameter is empty.
  • Throws a \ValueError exception if the $length is <= 0.
  • Throws a \Random\BrokenRandomEngineError exception if the underlying engine failed to generate a random byte sequence in the requested length.

Usage Examples

Generate a string containing five characters using characters from Douglas Crockford base32.

$rng = new Random\Randomizer();
$crockfordAlphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';

$rng->getBytesFromString($crockfordAlphabet, 5); // "5YH8T"
$rng->getBytesFromString($crockfordAlphabet, 5); // "XBZ9P"
$rng->getBytesFromString($crockfordAlphabet, 5); // "3TF6Y"
$rng->getBytesFromString($crockfordAlphabet, 5); // "MZD6N"

Generate a string only containing AEIOU.

$rng = new Random\Randomizer();
$chars = 'AEIOU';

$rng->getBytesFromString($chars, 1); // "E"
$rng->getBytesFromString($chars, 5); // "AIIEO"
$rng->getBytesFromString($chars, 10); // "IEAUAIIOUE"

Generate a random string with skewed probabilities:

$rng = new Random\Randomizer();
$chars = 'AAAAAABBC';

$rng->getBytesFromString($chars, 1); // "A"
$rng->getBytesFromString($chars, 5); // "ACBAC"
$rng->getBytesFromString($chars, 10); // "ACAABAAABAAAAAC"

Related Changes

Backwards Compatibility Impact

\Random\Randomizer::getBytesFromString() is a new class method added to the PHP Random extension in PHP 8.3. Randomizer class is declared as final.

It is possible for user-land PHP polyfills for the Random extension's Randomizer class to implement the new getBytesFromString method.


RFC Discussion Implementation