Edit in GitHubLog an issue
Thanks to Adarsh Manickam for contributing this topic!

Math random

The Magento\Framework\Math\Random library provides the ability to generate random values and hashes.

Usage#

MethodDescription
getRandomStringGenerates a random string with a given string length and an optional character pool. Without the optional character pool, it uses both cases of the English alphabet and all digits.
getRandomNumberGenerates a random number with an optional range. The range defaults to 0 as minimum and the result of the PHP function mt_getrandmax as the maximum.
getUniqueHashGenerates a unique hash string with an optional prefix.

Examples#

In the examples below, the $this->mathRandom property is an instantiated object of the Magento\Framework\Math\Random class.

Generate a random string#

This example shows how to generate a random string of length 99, with the default character pool.

Copied to your clipboard
$this->mathRandom->getRandomString(99);

Generate a random number#

This example shows how to generate a random number between 0 and 9999.

Copied to your clipboard
$this->mathRandom->getRandomNumber(0, 9999);

Generate a random number#

This example shows how to generate a unique hash string with a prefix.

Copied to your clipboard
$this->mathRandom->getUniqueHash("my_hash_prefix");
Was this helpful?
  • Privacy
  • Terms of Use
  • Do not sell my personal information
  • AdChoices
Copyright © 2022 Adobe. All rights reserved.