PHP : Random string with numbers and letters
Posted on October 1st, 2007 by lost-in-code
I thought that some of you might find it useful to learn how to generate a string with random numbers and letters. I wrote a quick function for generating a string like this. See it below :
function genRandomString() {
$length = 10;
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
$length = 10;
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyz’;
$string = ”;
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
Tags: letters, numbers, php, random, random string, string
Filed under: PHP

Nice, came across this with a quick google search.
You have some syntax incorrect though. As it is now it will return something like 1f’q4w’432″2 - You don’t want those odd characters in there right?
Remove $string = “; it will get defined anyway. Also replace the ‘ around the $characters declaration and replace it with ” - it should look like this:
$characters = “0123456789abcdefghijklmnopqrstuvwxyz”;
That will mean the return will only have letters and numbers
Hi Jake,
Thank you for the comment.
It is the encoding of Wordpress which causes those entities.
In reality, you have to replace them with proper html characters when you use the code. Here is a sample :
http://lost-in-code.com/wp-content/_randomstring.php
It works well.
All the best,
Antonie
Oh then I do apolosgize! Didn’t consider WP might be screwing things up.
But thank you for the snippet there. I used it in http://www.jakeisonline.com/s/ - something I was working on for work.
Thanks!
Also found this via google. Nice function, just wanted to drop a line and say thanks, I used this for my blog.