General Question

richardhenry's avatar

PHP Gurus: What is the easiest way to generate a specified length string of random alpha characters?

Asked by richardhenry (12659points) July 8th, 2008

For example: XHAOP; KFDOW; MCHSO. What’s the most efficient way to do this?

Observing members: 0 Composing members: 0

4 Answers

Breefield's avatar

Well, this code will spit stuff out per your “For example”
Not sure what alpha characters are though…

for($i = 0; $i < 5; $i++) {
     $string = ’’;
     for($j = 0; $j < 5; $j++) {
          $string .= chr(65 + rand() % 25);
     echo $string.’; ’;

Check it here.

richardhenry's avatar

Thanks Breefield, you legend. :)

Oh, and I meant ‘alpha’, as in ‘alphabet’.

robmandu's avatar

@richardhenry, I think you’re getting what you want, but just pointing out that that example will only ever return UPPERcase chars (the chr function in PHP returns a character based on the ASCII integer value provided.) You’d need to add some more complexity to get a mix of lowercase chars and/or numerics.

Also note that @bree modulo’d with 25… because it’s counting like 0, 1, 2…, 25 to get the twenty-six unique values for each letter of the alphabet.

richardhenry's avatar

@rob: Yeah noticed that. It probably would have tripped me up the first time I did it had I been doing this myself.

And yeah; caps is what I need. :) Again, thanks for giving such a great example Breefield.

Answer this question




to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
Knowledge Networking @ Fluther