Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: creating a string of random numbers and letters

1. ## creating a string of random numbers and letters

I know how to use rand() to create a random number but how can i create a string that is 7 charactors that is a mixture of numbers and letters. Thanks.

• I don't know if there is a function that can do this. You could possibly use two random number generators, one to chose between an array of letters or numbers and the second to either choose which letter (position) in the array or a random number. That is the only way that comes to me right now...off the top of my head....

Jason

• so you can do rand(a,z)?

• not that I know of....do a random number from 1-2 that will chose whether you are putting in your 7element array or whatever a number or letter....then the next one would be say for letter: a number that is from 1-26 for each letter of the alphabet and then for number: would be a random number....and loop 7 times....does that make sense?

Jason

• okay this is what i made..

<?php

\$v = 1;
while(\$v <= 7)
{
\$randnumberagain = rand(1,4);
if(\$randnumberagain%2)
{
\$randome_alph = rand(1,26);

}
else
{
}
\$randstr = \$randstr;
\$v++;
}
\$randstr = strtoupper(\$randstr);
echo \$randstr;
?>

• \$randstr[7];
for (\$i =0; \$i < 7; \$i++){
\$j = rand(1,2);
if (\$j ==1){ //alphabet
\$alpha = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y' ,'z'}
\$k = ran(0,25);
\$randstr[\$i]=\$alpha;
}
else { //numbers
\$randstr[\$i] = \$ran(0,9);
}
}

thats an ugly way...didn't test this but you get the idea....

Jason

• uniqid() creates a random string... its mostly numeric but you can manipulate that somewhat , the last version here produces an alpha-numeric mixed case unique string pretty good for password generation etc, grabbing the last 7 characters gives better values for whatever reason (I assume because uniqid works on the current timestamp?)

PHP Code:
``` <? echo substr(uniqid(""),-7).'<br />'; echo substr(md5(uniqid("")),-7).'<br />'; echo substr(base64_encode(md5(uniqid(""))),-7); ?> ```

• I think:

PHP Code:
``` \$str = ''; for(\$i = 0; \$i < 7; \$i++)  {       \$str .= chr(rand(ord("a"),ord("Z"))); }  ```
Hope this helps...

• \$str = substr(md5(rand(0,99999)),0,7);

seems fastest. might need to salt the rand if your build is oldish though.

• thanks much

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•