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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改