To answer this question specifically, two problems:
(要具体回答这个问题,有两个问题:)
-
$randstring
is not in scope when you echo it. (当您回显它时, $randstring
不在范围内。)
- The characters are not getting concatenated together in the loop.
(这些字符在循环中没有并置在一起。)
Here's a code snippet with the corrections:
(这是包含更正的代码段:)
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Output the random string with the call below:
(通过以下调用输出随机字符串:)
// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
Please note that this generates predictable random strings.
(请注意,这会生成可预测的随机字符串。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…