Entry
Intro level - I want to provide a set of four or five random responses to each different answer to a question. How do I do that?
May 17th, 2001 08:39
Philip Olson, Richard Stohlman,
Let's say you have an array full of responses, such as :
$a = array('yes','no','maybe','never','sometimes','perhaps','hmm');
Let's create a quick function to select a few ($num) of these answers,
many ways exist to do this such as :
function getRandomAnswers($answers,$num)
{
mt_srand ((double) microtime() * 1000000);
shuffle($answers);
return array_slice($answers,0,$num);
}
Which will return an array with $num random answers from $answers
array. You'll print out the elements from this array to your user,
perhaps like so :
function returnRandomAnswers($answers)
{
$t = '<ul>';
foreach ($answers as $answer) {
$t .= "<li><a href='foo.php?reply=$answer'>$answer</a>";
}
$t .= '</ul>';
return $t;
}
Hopefully the above gives the general idea.