Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random string? 1

Status
Not open for further replies.

JRBeltman

IS-IT--Management
Joined
Feb 5, 2004
Messages
290
Location
NL
Hi all,
I found a nice piece of code on php.net.
It works well, but I do not understand all of this

Code:
for($len=10,$r='';strlen($r)<$len;$r.=chr(!mt_rand(0,2)?
mt_rand(48,57):(!mt_rand(0,1)?mt_rand(65,90):mt_rand
(97,122))));


Can anyone tell me what happens exactly in
(!mt_rand(0,2)?
mt_rand(48,57):(!mt_rand(0,1)?mt_rand(65,90):mt_rand
(97,122)))

I am aware of the function of mt_rand, but do not understand this code :-(


JR
As a wise man once said: To build the house you need the stone.
Back to the Basics!
 
I don't know who wrote that gobbledygook, and it may work, but it's a very bad coding style. It's unreadable and thus difficult to maintain. The author probably thought he was being cute.

Reformatting the segment as:

Code:
for
(
	$len=10,$r='';
	strlen($r)<$len;
	$r.=
		chr
		(
			!mt_rand(0,2)?
			mt_rand(48,57):
			(
				!mt_rand(0,1)?
				mt_rand(65,90):
				mt_rand(97,122)
			)
		)
);

You can see that whoever wrote that is using ghastly nested trinary operators to generate random numbers according to some kind of distribution.

The following code should be a functional equivalent:

Code:
$len = 10;
$r = '';

while (strlen($r) < $len)
{
	$a = mt_rand(0,2);

	if ($a != 0)
	{
		$a = mt_rand(48,57);
	}
	else
	{
		$a = mt_rand(0,1);

		if ($a != 0)
		{
			$a = mt_rand(65,90);
		}
		else
		{
			$a = mt_rand(97,122);
		}
	}

	$r .= chr($a);
}


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
very neat! [medal] for you.

Thanks

JR
As a wise man once said: To build the house you need the stone.
Back to the Basics!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top