Home > Backend Development > PHP Tutorial > PHP生成指定长度随机数最简洁的方法_php实例

PHP生成指定长度随机数最简洁的方法_php实例

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 17:17:28
Original
808 people have browsed it

刚才在写短信验证码模块,需要用到指定位数的随机数,然后网上一找发现太可怕了这么简单的事情竟然用了好几十行多个循环嵌套……看来没有好脑仁儿真的不适合当程序员。

自写了一行版本:

function generate_code($length = 4) {
    return rand(pow(10,($length-1)), pow(10,$length)-1);
}

Copy after login

为了便于理解,同时也为了这篇水文可以凑点字数,这是多行版:

function generate_code($length = 4) {
    $min = pow(10 , ($length - 1));
    $max = pow(10, $length) - 1;
    return rand($min, $max);
}
Copy after login

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template