Jump to content

Generate a random String and then concatenate it with another one


g_p_java

Recommended Posts

Hello,

 

i would like to generate a random string in PHP using the characters 1,2,...9,0,a,...,z,A,...Z.

and then concatenate the random string with another string

 

May you please tell me what shall i study in order to do that?

 

thanks in advance!

Not sure what to instruct you to study other than the PHP manual in general :P

 

Here is a function for generating random strings:

 

function generateRandom($length = {
	// A list of characters permitted to be part of the generated string
	$allowed_chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

	// The length of the above string, minus 1 ( array/string indexes start at 0 not 1 )
	$allowed_length = strlen($allowed_chars) - 1;

	// make sure PHP knows that we want to consider $str as a string
	$str = '';

	for($i = 0; $i < $length; $i++){	// loop how many characters we want
		// generate a random number to be used as the index
		$index = mt_rand(0, $allowed_length);
		// add the character at $index of $allowed_chars to our string
		$str .= $allowed_chars[$index];
	}

	// return random string
	return $str;
}

 

You would gather this random string and concat it to another with:

 

$newString = generateRandom(20) . 'otherstring';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.