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

How to generate php random numbers from numbers and letters

黄舟
Release: 2023-03-17 10:08:01
Original
2440 people have browsed it

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;
}
Copy after login

For example, randomly generate 2 A combination of letters and numbers
Just call the function and pass parameter 2.

echo getRandomString(2);
Copy after login

If you only generate lowercase letters, you can use a similar method

echo chr(mt_rand(65, 90);
Copy after login

Uppercase letters

echo chr(mt_rand(97, 122));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template