我有一个导致上述错误反复出现在我的错误日志中的代码,我该如何纠正它?

public function generate_guid() {
        //you can change the length of the autogenerated guid here
        //i choose 4 because with 26 possible characters that still gives 456.976 possibilities, if you include numbers ( add 0123456789) to the possible characters you will get 1.679.616 combinations
        $length = 4;
         //charachters used for string generation
    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $string = '';
    for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters))]; <<-- this is line 92
}
return $string;
    }

最佳答案

问题是mt_rand(0, strlen($characters))会生成直至字符串长度的数字-但是当字符串偏移量从0开始时,最大偏移量就是长度减去一。因此正确的是mt_rand(0, strlen($characters) - 1)

顺便说一句,我建议使用range('a', 'z')生成的字符数组(这样就不必键入它),并建议使用array_rand获取元素。

关于php - 生成随机GUID时未初始化的字符串偏移量通知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7920109/

10-12 21:23