Tag Archives: generate random string

PHP: How to Generate a Random String Containing Both Letters and Numbers Programming 11 MAY 2012

To generate a string containing a random selection of both letters and numbers (i.e. an alphanumeric string) using PHP is pretty trivial.

Essentially what we want to do is define a string containing all the characters we wish to use in the generated string. Then randomly select characters from the string and glue them all together until we get a random string of the desired length.

Coded as a function, you get:

function rand_string( $length = 5 ) {
	$str = ''; //the resulting random string
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	 //characters making up the random string

	$size = strlen( $chars );

	return $str;

Pretty simple, but quite useful actually.