Notice: Uninitialized string offset: -1

A web page is returning Notice: Uninitialized string offset: -1…..on line 175 whe running the function below:

function genRandomString() {

    $length = 26;

    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';

    $string = "";    

    for ($p = 1; $p < $length; $p++) {

    $string .=$characters[mt_rand(0, strlen($characters))-1]; // <-- LINE 175

    }

    return $string;

    }

What might be the problem on the line 175?

Answer

You need to subtract from strlen, not from mt_rand:

mt_rand(0, strlen($characters) - 1)

function genRandomString($length = 26) {
    $characters = implode('', range(0, 9)) . implode('', range('a', 'z'));

    $string = '';
    $maxIndex = strlen($characters) - 1;

    for ($i = 1; $i < $length; $i++) {
        $string .= $characters[mt_rand(0, maxIndex)]; // <-- LINE 175
    }

    return $string;
}

Leave a Reply

Your email address will not be published. Required fields are marked *