Guys, I got a stupid noob question

Say I want to fill variable $query with a random one character string picked randomly from a letter a-z with equal probability.

How would I do so?

So, $query can be 'a', maybe , 'q', maybe whatever, each with 1/26th probability.

Thanks a lot.

    $arr = range('a', 'z');
    $rand_char = $arr[mt_rand(0, count($arr) - 1)];

      Excelent. Of course, if I work hard I can probably come up with a solution, but my solution won't be as ellegant as those provided by super guru here 😃

        Except my original answer won't work. 🙂 See the edited code.

        Here's another one:

        $arr = range('a', 'z');
        $rand_char = $arr[array_rand($arr)];

        Or, essentially the same thing:

        $arr = array_flip(range('a', 'z'));
        $rand_char = array_rand($arr);

          <php>
          $arr = array_flip(range('a', 'z'));
          $rand_char = array_rand($arr);
          </php>

          I used this one. It works perfectly. Thanks a lot.

            An "array-free" possibility:

            $rand_char = chr(rand(ord('a'), ord('z')));
            

              better and better.

              What about if I want to randomize between a-z and 0-9 each with equal probability?

                I use something like this for generating random "captcha" strings:

                $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
                $randChar = $chars[rand(0, strelen($chars) - 1)];
                

                It's not necessarily better/worse than the array-based options, but I found it useful because it was easy to manipulate. For instance, if I want to increase the possibility of a the selected character being a number, and I want to avoid certain characters that could be confusing (o or 0, l or 1, i or j, u or v):

                $chars = 'abcdefghkmnpqrstwxyz2233445566778899';
                

                  NogDog's solutions are better, but just for interest here's an array-based one:

                  $arr = array_flip(array_merge(range('a', 'z'), range('0', '9')));
                  $rand_char = array_rand($arr);

                  For not array-based, this one will work but is a little clumsy:

                  $ord = 58;
                  while (($ord > 57) && ($ord < 97)) {
                      $ord = mt_rand(48, 122); 
                  }
                  $rand_char = chr($ord);
                    6 days later

                    Personally, I use something like what NogDog described, but Installer's solutions are interesting.

                      Write a Reply...