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

	return $str;

Pretty simple, but quite useful actually.

How to create a Variable Length String of Random Characters using JavaScript Programming 04 MAY 2012

Generating random strings is always necessary when working with things like voucher or password generation, and so today’s quick JavaScript function looks at returning a specified length of string containing a a selection of randomly selected characters and numbers.

The function works by specifying a string containing all the characters you wish to be used in your randomly generated string. Using the random() function and mixing it up a little to generate essentially a character position, we can grab a character off the previously mentioned character string. Rinse and repeat for the desired length of string, adding everything together to at last come up with your string of random characters.

function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	return randomstring;

Nice and random, just like this image.