Home > php教程 > php手册 > body text

php如何随机生成数字与字母的组合

PHPz
Release: 2018-10-17 15:49:43
Original
2483 people have browsed it

这篇文章主要介绍了php随机生成数字字母组合的方法,实例分析了php生成随机数及随机字母的相关技巧与用法,非常具有实用价值,需要的朋友可以参考下

直接上代码:

代码如下:

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

例如随机生成 2 位 字母和数字组合
只需调用函数 并传参2即可。

echo getRandomString(2);
Copy after login

如果仅仅是生成小写字母你可以使用类似方法

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

大写字母

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

 

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template