PHP随机字符串生成器
我正在尝试在PHP中创建一个随机字符串,并且我对此绝对没有输出:
<?php function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我究竟做错了什么?
回答:
要具体回答这个问题,有两个问题:
$randstring
当您回显它时,它不在范围内。- 这些字符在循环中没有并置在一起。
这是包含更正的代码段:
function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
通过以下调用输出随机字符串:
// Echo the random string.// Optionally, you can give it a desired string length.
echo generateRandomString();
以上是 PHP随机字符串生成器 的全部内容, 来源链接: utcz.com/qa/429231.html