Jump to content

generating random string


knobby2k

Recommended Posts

Hi guys,

 

I have a piece of code that generates a random 10 character string but occasionally kicks up an error, please see the example code below...

 


function genRandomString() {
    $length = 10;
    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY";
$string = "";	
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

 

Occasionally produces the error at the top of the page...

 

Notice: Uninitialized string offset: 61 in /websites/... and points to line 27 of my code which is the " $string .= $characters[mt_rand(0, strlen($characters))]; " line of the code in the example above.

 

Is my code incorrect? Why would it produce an error sometimes but work perfectly fine others??

 

Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/239557-generating-random-string/
Share on other sites

$characters is not an array, but you are trying to use it like an array.

 

Try this instead:

$characters = array_merge(range(0,9),range('a','z'),range('A','Z'));

 

EDIT: You'd need another small modification too:

 

Change:

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

 

To:

$string .= $characters[mt_rand(0, count($characters)-1)];

as further information, your script was not working because you were trying to address a string as an array. When using the array syntax on a string, it breaks down each character of a string as values...example

$string = "Hello World";
echo $string[0];//outputs H
echo $string[3];//outputs l

etc. What was happening were there were times when your script would produce use the maximun strlen of your $characters var, so you would have

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY[61];

which would put your pointer one character after the full string, which cant be done, thus the error is triggered for invalid offset

 

as further information, your script was not working because you were trying to address a string as an array. When using the array syntax on a string, it breaks down each character of a string as values...example

$string = "Hello World";
echo $string[0];//outputs H
echo $string[3];//outputs l

etc. What was happening were there were times when your script would produce use the maximun strlen of your $characters var, so you would have

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY[61];

which would put your pointer one character after the full string, which cant be done, thus the error is triggered for invalid offset

 

thanks for the explanation, makes perfect sense now!!

 

Cheers guys

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.