使用现有代码在PHP中生成随机数

时间:2015-02-08 19:48:42

标签: php random numbers

我正在使用以下代码并获得6个随机字符。如何将字符数增加到10(或任何其他数字)?这段代码中的内容是6个字符?

function createRandomID() {

$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";

$i = 0;

$pass = "";

while ($i <= 5) {

$num = rand() % 33;

$tmp = substr($chars, $num, 1);

$pass = $pass . $tmp;

$i++;

}
return $pass;
}

1 个答案:

答案 0 :(得分:1)

您已经得到了正确的答案,因此您的代码变为:

function createRandomID() {

$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";

$i = 0;

$pass = "";

$upTo = 9 // if you want 10 or whatever - 1

while ($i <= $upTo) {

$num = rand() % 33;

$tmp = substr($chars, $num, 1);

$pass = $pass . $tmp;

$i++;

}
return $pass;
}