0

When Im running the next code:

function RandomLink()
        {
        $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
        $string = "";
        for($x = 0; $x< 30; $x++)           
            {
              $string .= $characters[(mt_rand(0, strlen($characters)))]; // Random char
            }

        return "$string.php";
        }

I get an error which says: Uninitialized string offset .What it mean's and how can i fix it? I just dont want programming like a robot,I want understands behind the error may someone explain me too? Thank you very much !

4
  • 2
    Try replacing strlen($characters) with strlen($characters) - 1 Commented Aug 2, 2013 at 15:23
  • Worked thanks ! It was because the string length was too long ? Commented Aug 2, 2013 at 15:24
  • Yeah. Since the index starts at 0, the last index in the string is actually 1 less than the length Commented Aug 2, 2013 at 15:25
  • It's because the string is 0-indexed to 35 and your mt_rand goes from 0 to 36. Commented Aug 2, 2013 at 15:25

2 Answers 2

2

Your problem is that mt_rand parameter max is inclusive. So strlen($characters) should be strlen($characters)-1 since there is no character at the index equivalent of the length of the string.

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

If your string was length of 2 like "ab" then mt_rand(0, 2) would return values 0, 1, and 2, which is a, b, and JUST ONE TOO FAR.

Sign up to request clarification or add additional context in comments.

Comments

0

As noted in the comments, the offset you provided to mt_rand() is beyond $characters length. Update the strlen($characters) - 1.

Also, you've recreated - str_shuffle():

Consider refactoring to:

function RandomLink() {
  $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
  $hash = str_shuffle($characters);
  return substr($hash, 0, 30) . '.php';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.