本文介绍了PHP随机字符串生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在PHP中创建一个随机字符串,并且我绝对不会得到任何输出:
I'm trying to create a randomized string in PHP, and I get absolutely no output with this:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我在做什么错了?
推荐答案
要专门回答此问题,有两个问题:
To answer this question specifically, two problems:
- 回显
-
$randstring
不在范围内. - 这些字符在循环中没有并置在一起.
$randstring
is not in scope when you echo it.- 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();
这篇关于PHP随机字符串生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!