Posted in tutorials, web | January 19th, 2010 | Comments: 0

I have written a simple function to generate a random string in PHP. It was made to generate a string with uppercase, lowercase and numeric values. It can be modified to accept any ASCII characters and can generate a string of any length.

This function may also help understanding passing variables by reference and recursion.

Function

function generateRandomString( $length, &$string )
{
	// RANDOM TO CHOOSE 1. UPPERCASE / 2. LOWERCASE / 3. NUMBER
	$which = mt_rand( 1, 3 );
	switch( $which )
	{
		case 1:
			$min = 65; $max = 90;
			break;
		case 2:
			$min = 97; $max = 122;
			break;
		case 3:
			$min = 48; $max = 57;
			break;
	}

	// GET RANDOM NUMBER FOR CHARACTER
	$rand = mt_rand( $min, $max );

	// CONVERT ASCII TO CHAR AND APPEND TO STRING
	$string .= chr( $rand );

	// IF EQUAL TO OR GREATER THAN LENGTH THEN RETURN
	if( strlen($string) >= $length ) return;

	// RECURSION - BUILD THE STRING
	generateRandomString( $length, $string );
}

Usage

Posted by Beau Durrant

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Ping This!