Page 1 of 1

Rand feature creating a string for a variable[solved]

Posted: Fri Aug 17, 2007 6:16 pm
by SirChick
Hello,

Im quite new to using rand features in php. Im trying to figure out how to do something like this:

Randomly choose one of these 5 lines:

$QuoteResult = 'Result: You search the train station from top to bottom and find $1!'
$QuoteResult = 'Result: You search the train station from top to bottom and find $3!'
$QuoteResult = 'Result: You search the train station from top to bottom and find $5!'
$QuoteResult = 'Result: You search the train station from top to bottom and find $8!'
$QuoteResult = 'Result: You search the train station from top to bottom and find $10!'

Reason i do it like this is cos then i just echo $QuoteResult ... seems to be easier but im unsure how to structure it.

Posted: Fri Aug 17, 2007 6:29 pm
by superdezign

Code: Select all

$choices = array('Choice #1', 'Choice #2', 'Choice #3');
echo $choices[mt_rand(0, sizeof($choices) - 1)];
:?:

Posted: Fri Aug 17, 2007 6:31 pm
by kaszu
First put all these in an array and then select random line with array_rand:

Code: Select all

$QuoteResults = array();
$QuoteResults[] = 'Result: You search the train station from top to bottom and find $1!';
$QuoteResults[] = 'Result: You search the train station from top to bottom and find $3!';
$QuoteResults[] = 'Result: You search the train station from top to bottom and find $5!';
$QuoteResults[] = 'Result: You search the train station from top to bottom and find $8!';
$QuoteResults[] = 'Result: You search the train station from top to bottom and find $10!';

$QuoteKey = array_rand($QuoteResults);
$QuoteResult = $QuoteResults[$QuoteKey];
That's it :)
Edit: i guess i'm typing too slow :(

Posted: Fri Aug 17, 2007 6:39 pm
by SirChick
works a treat! Thankyou guys!!!