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

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

WBOY
Release: 2016-06-06 20:20:02
Original
1066 people have browsed it

这篇文章主要介绍了PHP生成指定长度随机数最简洁的方法,一行代码搞定随机数生成,是不是最简洁、最优雅的方法,需要的朋友可以参考下

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

自写了一行版本:

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

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

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

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