Jump to content

Random String Generation?


random1

Recommended Posts

<?php

$uletter= mt_rand(65,90);// Upper case letters.
echo chr($uletter);

$uletter= mt_rand(97,122);// lower case letters.
echo chr($uletter);

$uletter= mt_rand(48,57);// Numerica numbers.
echo chr($uletter);

$uletter= mt_rand(32,47);// Symbol.
echo chr($uletter);
?>

 

http://www.ascii.cl/htmlcodes.htm

This forum is to get help with code you have written. have you even attempted this?

 

Yeah I attempted it using mt_rand like voip03 did, but his is far more elegant. I'll get started on this now :D

 

Well, it will get somewhat complicated (or inefficient) to use that logic while enforcing the requirement for no repeating characters. I have a fairly easy implementation in mind, but I want to at least see you make an attempt rather than just writing it for you.

Here's a hint - using an array and shuffle() will make things easy. array_slice() can be used to get only part of an array. range() can be used to generate a range of ASCII characters into an array.

 

That's your solution. Give an attempt to code it and we'll help further.

I ended up using:

 

function rand_str($len, $norepeat = true)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
$max = strlen($chars) - 1;

if($norepeat && $len > $max + 1)
{
	throw new Exception('Non repetitive random string can\'t be longer than charset');
}

$rand_chars = array();

while($len)
{
	$picked = $chars[mt_rand(0, $max)];

	if($norepeat)
	{
		if(!array_key_exists($picked, $rand_chars))
		{
			$rand_chars[$picked] = true;
			$len--;
		}
	}
	else
	{
		$rand_chars[] = $picked;
		$len--;
	}
}

return implode('', $norepeat ? array_keys($rand_chars) : $rand_chars);   
}

echo rand_str(32, true);

 

Sample output: bkWfyRME%qYHncUF$BjgPLxei5JdSmGs

 

I'll test it more but I'm rather happy with it  :D

OK, now that you have at least attempted it, I'll show you a more efficient method. You should avoid using loops for things when there are other methods at your disposal. That function is inefficient as it need to run a loop for each and every character - especially since it has to repeat whenever a duplicate character is encountered. That is just a waste.

 

Also, I would suggest not using variable names such as "$norepeat" - when the value is FALSE you have a double negative (by virtue of the no) which results in a true. If a variable is supposed to be true/false, name it such that it is more logical (i.e. $repeat). You can always check for a negative.

 

lastly, I would suggest making the list of characters as an additional parameter for the function. That give's you more flexibility.

 

Anyway, this will do the same thing in a much more efficient manner

function randomString($length, $charList, $repeat=false)
{
if(!$repeat && $length>strlen($charList))
{
	throw new Exception('Non repetitive random string can\'t be longer than charset');
    }
    //Create an array of the characters (add additional if needed)
    $charsAry = str_split(str_repeat($charList, ceil($length/strlen($charList))));
    //Randomize the array
    shuffle($charsAry);
    //Return the random string
    return implode(array_slice($charsAry, 0, $length));
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
echo randomString(32, $chars);

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.