Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Uninitialized string offset in PHP

Tags:

php

Hi I have this function and it returning a notice:

Notice: Uninitialized string offset

function generaterandomkey($length) {       

    $string='';
    $characters = "0123456789abcdef";
    for ($p = 0; $p < $length ; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];            
    }

    return $string;
}

The affected line is this:

$string .= $characters[mt_rand(0, strlen($characters))];

I have tried doing with braces and it does not work. If someone can point out some suggestions, I would highly appreciate it. Thanks.

like image 793
Emerson Maningo Avatar asked Jun 30 '26 16:06

Emerson Maningo


1 Answers

You are occasionally overrunning $characters because of strlen($characters), which should be strlen($characters) - 1. Your random range should begin with zero, and you need to end with the length minus one. If the length of $characters is 10, then the last zero-based array index is nine, and that becomes your upper bound for random selection.

$string='';
$characters = "0123456789abcdef";
for ($p = 0; $p < $length ; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters) - 1)]; 
}

Because you are choosing randomly, you wouldn't always receive the notice -- it would only occur if mt_rand() returned its maximum value at some point in your loop.

like image 127
Michael Berkowski Avatar answered Jul 03 '26 07:07

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!