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


Uninitialized string offset notice when generating random GUID

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

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开始,最大偏移量是长度减去1。所以正确的是mt_rand(0, strlen($characters) - 1)

顺便说一下,我建议使用由range('a', 'z')生成的字符数组(因此您不必将其键入)并使用array_rand获取元素。