Rand feature creating a string for a variable[solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SirChick
Forum Contributor
Posts: 125
Joined: Tue Jul 31, 2007 11:55 am

Rand feature creating a string for a variable[solved]

Post 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.
Last edited by SirChick on Fri Aug 17, 2007 6:40 pm, edited 1 time in total.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Code: Select all

$choices = array('Choice #1', 'Choice #2', 'Choice #3');
echo $choices[mt_rand(0, sizeof($choices) - 1)];
:?:
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Post 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 :(
SirChick
Forum Contributor
Posts: 125
Joined: Tue Jul 31, 2007 11:55 am

Post by SirChick »

works a treat! Thankyou guys!!!
Post Reply