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

报告相同问题?