Home  >  Article  >  Backend Development  >  How to generate php random numbers from numbers and letters

How to generate php random numbers from numbers and letters

黄舟
黄舟Original
2017-11-10 14:31:392400browse

We have introduced the method of generating random numbers in PHP before, but we have not introduced in detail what the generated PHP random numbers are. Then we will introduce to you the method of PHP randomly generating combinations of numbers and letters, and analyze the PHP generation with examples. The related skills and usage of random numbers and random letters are of great practical value. Friends in need can refer to it!

How to generate php random numbers from numbers and letters

function getRandomString($len, $chars=null)
{
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }  
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = &#39;&#39;, $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];  
    }
    return $str;
}

For example, randomly generate 2 A combination of letters and numbers
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);

Uppercase letters

echo chr(mt_rand(97, 122));

Summary:

Seeing this, I believe that many friends have a better understanding of the generation of random numbers in PHP. They can be composed of letters and numbers, as well as the upper and lower cases of letters. This article can serve as a starting point. I hope it will be helpful to your work. help!

Related recommendations:

Five ways to generate random numbers without repeating in php


#php random number generation method


php random number WeChat red envelope random Generating algorithm php version


#

The above is the detailed content of How to generate php random numbers from numbers and letters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn