I have a code snippet that generates a random code 10 character.

function generator($lenght=10)
{
     for($i = 0; $i <= $lenght; $i++)
     {
          $uniqKey .= chr(rand(97,122));
     }
     return $uniqKey;
}
$randomN = generator();

When echoed $randomN == ymtkasvaae

But when I change the code to a upper case it adds a character.

$code = strtoupper($randomN);

When output the $code == YMTKASVAAEI

I am confused by such an odd outcome...

    The strings appear to have the same number of characters to me...

    ymtkasvaaei
    YMTKASVAAEI

      That's really not odd at all. The string that is generated is completely random. Since you're not seeding your random number generator with anything, it will give you the same random string every time.

      This should help...

      http://www.php.net/srand

        Since you're not seeding your random number generator with anything, it will give you the same random string every time.

        cough You should read what you linked to 😉

          laserlight wrote:

          cough You should read what you linked to 😉

          Gah, my bad. I think I need some coffee...

            Sorry, the string adds 11 character at the end when I make it upper case. Iput it with a mistake. The function works fine. What is odd is that once the code is generated and I use it later to change to upper case an extra character appears at the end. The generated code is 10 chars long, but as you can see in the upper case code it's 11 chars long...

              You might want to provide the smallest and simplest code that demonstrates the problem. The only problems I see with your current code snippet are:
              1. The loop runs ($lenght+1) times, but you probably want it to run $lenght times. This is due to the fact that your loop condition is ($i <= $lenght) instead of ($i < $lenght) despite beginning the loop index from 0.
              2. For correctness' sake, $uniqKey should be initialised to a blank string before the loop. If it does not exist, then by right you cannot append to it.
              3. $lenght should probably be renamed $length

                laserlight, your magic worked again. I changed $i <= $lenght to $i < $lenght and the problem went away...

                  Write a Reply...