As you know, we could generate a random number or string using core PHP functions.
But, We can generate a random number or string with the help of core Magento\Framework\Math\Random class in Magento 2.
Using Random.php class we can generate a random string and random number with Magento Best Coding Practice and we don’t need to depend on PHP core function.
Let’s we create Block class and give you demo how to use Random class in our module.
<?php
namespace Mageclues\RandomGen\Block;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\Math\Random;
class Random extends \Magento\Framework\View\Element\Template
{
protected $_mathRandom;
public function __construct(
Context $context,
Random $mathRandom,
array $data = []
) {
$this->_mathRandom = $mathRandom;
parent::__construct($context,$data);
}
// generate number between specific range and return it.
public function getRandNumber($minimum = 0, $maximum = null)
{
return $this->_mathRandom->getRandomNumber($minimum, $maximum);
}
// Generate Random string and return it.
public function getRandString($length, $characters = null)
{
return $this->_mathRandom->getRandomString($length, $characters);
}
}
Now, you can call the block function in your template file and use return value.
// generate random digit between 1 to 7
<?= $block->getRandNumber(1,7); ?>
// generate 5 character long string from (A-Za-z0-9)
<?= $block->getRandString(5); ?>
We hope this blog is helpful for you.
Thank you!