我正在尝试在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 - PHP随机字符串生成器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4356289/