Home > Article > Backend Development > How to randomly generate a combination of numbers and letters in php, generate numbers and letters in php_PHP tutorial
The example in this article describes how to randomly generate a combination of numbers and letters in php. Share it with everyone for your reference. The details are as follows:
Go directly to the code:
Copy code The code is as follows: function getRandomString($len, $chars=null)
{
If (is_null($chars)){
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
mt_srand(10000000*(double)microtime());
for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i ){
$str .= $chars[mt_rand(0, $lc)];
}
Return $str;
}
For example, randomly generate a 2-digit letter and number combination
Just call the function and pass parameter 2.
echo getRandomString(2);
If you only generate lowercase letters, you can use a similar method
echo chr(mt_rand(65, 90);
Capital letters
echo chr(mt_rand(97, 122));
I hope this article will be helpful to everyone’s PHP programming design.