Generate Random String using Randomizer Class in PHP 8.3

Generate Random String using Randomizer Class in PHP 8.3

A random string is a sequence of characters created by a generator, with an unpredictable result and no recognizable pattern. PHP provides a Randomizer class for generating random values. Since PHP 8.3, this class has a new getBytesFromString method which generates a random string with a specified length, composed of randomly selected bytes from a given string.

<?php

use Random\Randomizer;

$rnd = new Randomizer();

$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
echo $rnd->getBytesFromString($chars, 10); // 10-character random string

Keep in mind that the getBytesFromString method operates at the byte level and may not effectively shuffle multibyte characters, such as those in UTF-8 encoding. However, this method can be useful to generate random identifiers, such as domain names, voucher codes, and other alphanumeric strings.

Leave a Comment

Cancel reply

Your email address will not be published.