生成随机GUID时未初始化的字符串偏移通知

时间:2011-10-27 17:47:39

标签: php syntax-error

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

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;
    }

1 个答案:

答案 0 :(得分:4)

问题是mt_rand(0, strlen($characters))将生成最多为字符串长度的数字 - 但是当字符串偏移量从0开始时,最大偏移量是长度减去1。所以正确的是mt_rand(0, strlen($characters) - 1)

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