There comes a time when you need to create a random String. It might be for a verification code, a complex password, or something you are developing. You might think that its a boring and manual process. Luckily, this is not true.

Below we present a simple way to create random Strings using PHP. All you need is one function with a few lines of code. Let’s begin…

The Function

Let’s call this function rand_string. It will require one parameter, $length, that represents the length of the String to produce:

function rand_string( $length ) {

}

Our first priority is to create a String of our own with all the letters that may be used in the random String:

$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

We will refer to parts of this String using a random generator. Once we generate a random integer index, we add the corresponding character – the character at that index – to a finished String. This can be completed using a loop:

$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
	$str .= $chars[ rand( 0, $size - 1 ) ];
}

Alternatively, Bob (see comment below) suggested that you may use the str_shuffle function, which will randomly move characters around in the String. By using a simple substr snippet, it’s possible to cut this String down to the specified length.

$str = substr( str_shuffle( $chars ), 0, $length );

Note: If you require a random String that has a greater length than $chars itself, this alternative method will not work.

After that, we can just return the String.

function rand_string( $length ) {
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	

	$size = strlen( $chars );
	for( $i = 0; $i < $length; $i++ ) {
		$str .= $chars[ rand( 0, $size - 1 ) ];
	}

	return $str;
}

Usage

Using this function now becomes a walk in the park. Just pass in the length of a random String you want to generate, and store the returned value in a variable:

$my_string = rand_string( 5 );

Customization

To customize this generator to meet your needs, you may edit the $chars variable to only contain the characters of your choice. The rest of the code need not be changed.

That’s all there is to it. Thanks for reading!

Leave a Reply

Creating A Random String With PHP