Home  >  Article  >  Backend Development  >  PHP怎么生成指定长度随机数?

PHP怎么生成指定长度随机数?

PHPz
PHPzOriginal
2016-06-01 11:51:572828browse

PHP中生成指定长度随机数的方法:1、通过循环来指定长度;2、每经历一次循环,就使用“mt_rand()”函数生成一个随机整数;3、在循环中,将生成的单个随机数拼接起来,生成指定长度的随机数。

PHP怎么生成指定长度随机数?

PHP怎么生成指定长度随机数?

下面直接通过代码来看看:

<?php
$code = &#39;&#39;;
for ($i=1;$i<7;$i++) {         //通过循环指定长度
    $randcode = mt_rand(0,9);     //指定为数字
    $code .= $randcode;
}
 
echo $code;
?>

输出:7位数的随机数

356429

mt_rand() 函数使用 Mersenne Twister 算法生成随机整数。

提示:该函数是产生随机值的更好选择,返回结果的速度是 rand() 函数的 4 倍。

提示:如果您想要一个介于 10 和 100 之间(包括 10 和 100)的随机整数,请使用 mt_rand (10,100)。

更多相关知识,请访问 PHP中文网!!

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