jeradb Posted May 7, 2012 Share Posted May 7, 2012 Hi, I am new to the forums. I am having an issue with a snippet of code that generates random strings. I have already searched the forums, but the fix that I found is already in my code. I am still receiving the error though and was wondering if there was something else going on that I didn't see. Here is my code: $Data = 'Ahmet'.md5(mt_rand(0, 123456789)); $length = 30; $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $string = ''; $string2 = ''; for ($a = 0; $a < $length; $a++) { $pos = mt_rand(0, strlen($chars)-1); $string .= $chars{$pos}; $pos2 = mt_rand(0, (strlen($Data))-1); $string2 .= $chars{$pos2}; } I appreciate any help on this, as it is cluttering my system log table. Thanks. Link to comment https://forums.phpfreaks.com/topic/262201-php-error-uninitialized-string-offset-36/ Share on other sites More sharing options...
Muddy_Funster Posted May 7, 2012 Share Posted May 7, 2012 have you tried something more conventional like: for ($a = 0; $a < $length; $a++) { $pos = mt_rand(0, strlen($chars)-1); $string .= substr($chars, $pos, 1); $pos2 = mt_rand(0, (strlen($Data))-1); $string2 .= substr($chars, $pos2, 1); } the other thing I will say is that your $Data is likely a good bit longer than your $chars, so watch out for that returning a $pos2 that is outside the range of $chars. Link to comment https://forums.phpfreaks.com/topic/262201-php-error-uninitialized-string-offset-36/#findComment-1343748 Share on other sites More sharing options...
jeradb Posted May 7, 2012 Author Share Posted May 7, 2012 Thanks, I'll give that a shot. I was guessing that $Data was probably too long as well. Link to comment https://forums.phpfreaks.com/topic/262201-php-error-uninitialized-string-offset-36/#findComment-1343778 Share on other sites More sharing options...
jeradb Posted May 7, 2012 Author Share Posted May 7, 2012 Sorry for the double post, but I realized what I did wrong. I used $chars for $string2 instead of $Data. Once I changed it, everything worked fine. for ($a = 0; $a < $length; $a++) { $pos = mt_rand(0, strlen($chars)-1); $string .= $chars{$pos}; $pos2 = mt_rand(0, strlen($Data)-1); $string2 .= $Data{$pos2}; } Link to comment https://forums.phpfreaks.com/topic/262201-php-error-uninitialized-string-offset-36/#findComment-1343784 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.