How to generate random string or number in Magento 2?

In Magento 2, You can generate a random number or random string using core Magento\Framework\Math\Random class.

Using Random.php class you can generate a random string and random number with Magento Best Coding Practice and you don’t need to depend on PHP core function.

I have created a Block PHP file to add function( ) for a demo,

To generate random string Magento native uses a character,
const CHARS_LOWERS = ‘abcdefghijklmnopqrstuvwxyz’;
const CHARS_DIGITS = ‘0123456789’;

To Get Random digit number you need to pass range value in a function,

echo $this->getRandomNumber(1,7); // generate random digit between 1 to 7
echo $this->getRandomString(5); // generate 5 character long string from (A-Za-z0-9)