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 );
	for( $i = 0; $i < $length; $i++ ) {
		$str .= $chars[ rand( 0, $size - 1 ) ];

	return $str;

Pretty simple, but quite useful actually.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.