dounang1974 2017-04-08 02:15
浏览 63
已采纳

随机字符串生成器使字符串长度错误(PHP)

I'm trying to make a function that generates a random string, but the string is sometimes the wrong length.

function getRandomName($maxChars)
{
    $nameChars = str_split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
    $numOfChars = count($nameChars); // amount of characters in $nameChars
    $randomString = "";
    for($count=0;$count<$maxChars;$count++)
    {
        $randomInt = round(rand(0,$numOfChars));
        $selectedChar = $nameChars[$randomInt]; // random character in $nameChars
        $randomString .= $selectedChar; // adds to string
    }
    echo " ".strlen($randomString).", "; // length, string is echoed later
    return $randomString;
}
exit(getRandomName(6)); // 6 characters long

?>

Most of the time, the result will be something like 6, s2jd8q. But sometimes, the result is something like 5, d82kw. I only want strings that are 6 characters long, not 5. Anyone know how to fix this?

  • 写回答

5条回答 默认 最新

  • dqc18251 2017-04-08 02:24
    关注

    Edit $randomInt = round(rand(0,$numOfChars)); to $randomInt = round(rand(0,$numOfChars-1));

    If you run this

    $nameChars = str_split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
    $numOfChars = count($nameChars); // amount of characters in $nameChars
    //$numOfChars = 62
    
    echo($nameChars[61]); //Output: 0 (Last character)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办