-3

I have an FAQ page on my website, and I want to include a mini version on some other pages. The FAQ includes 21 questions and answers and I need a way, in PHP, that it can select 4 of those QAs at random to display on each page load.

I looked at using switch(), based on this article: http://php.about.com/od/finishedphp1/p/random_quote.htm but I need something about more complex because I don't want there to be any duplicates in the 4 that are displayed each time. One last thing, the text it randomly pulls will contain html, not just raw text.

I would really appreciate any help. Thanks.

Example:

I have used sample text to show what I mean:

   <? 
    //Chooses a random number 
    $num = Rand (1,2); 
    //Based on the random number, gives a quote 
    switch ($num)
    {
    case 1:
    echo "What does such and such mean?<br>It means this and that.";
    break;
    case 2:
    echo "How does this and that work?<br>It works via such and such.";
    break;

    }
    ?> 

But this would only randomly display 1 each time. I want 4 randomly displayed, but none of the 4 to be duplicates, hence why I'm not just copying & pasting the above code 4 times.

  • [**this**](http://stackoverflow.com/questions/4990752/how-i-can-generate-6-random-numbers-php), [**this**](http://stackoverflow.com/questions/4776553/php-generate-unique-and-random-numbers-ids?rq=1).... there is a search field above for a purpose. – itachi Oct 09 '13 at 16:19

2 Answers2

2

Load each paragraph into an array element. Shuffle the array, then output the first 4.

aynber
  • 22,380
  • 8
  • 50
  • 63
1

Take each paragraph and add it into an array. Select and remove a random entry from the array (random 0 to array.length)

Be sure to remove the item from the array once you select it.

Repeat the select and remove step 3 more times and you will have a no duplicate set from the original set of paragraphs.

Note: efficiency wise it might be better to through something like paragraph number into an array and select those, then convert paragraph number back to original paragraph.

voglster
  • 783
  • 6
  • 12