How do I randomise the contents returned in a foreach loop

Talk about writing modules and plugins for CMS Made Simple, or about specific core functionality. This board is for PHP programmers that are contributing to CMSMS not for site developers
Post Reply
applejack
Power Poster
Power Poster
Posts: 1014
Joined: Fri Mar 30, 2007 2:28 am
Location: London

How do I randomise the contents returned in a foreach loop

Post by applejack »

I am using cgsimple within a foreach loop to pull data from multiple pages and I need to randomise the output.

i.e. Say there are 10 pages and I need to show the contents of 4 but which 4 need to be randomised and of course it cannot show the same page content more than once. Also ideally the number should not be sequential i.e. it can show data in the order of page 5, 2, 9, 6.

Any ideas greatly appreciated.

Website Design & Production
http://www.applejack.co.uk
Wishbone
Power Poster
Power Poster
Posts: 1368
Joined: Tue Dec 23, 2008 8:39 pm

Re: How do I randomise the contents returned in a foreach loop

Post by Wishbone »

I found this doing a Google search for "php unique random" (without the quotes) and hit this page:

http://php.net/manual/en/function.rand.php (in the user comments section)

Code: Select all

$rand = array();
while (count($rand) < $total ) {
    $r = mt_rand($min,$max);
    if ( !in_array($r,$rand) ) {
        $rand[] = $r;
    }
}
Set $total to the number of random numbers that you want. Set $min to the smallest number you want to output, and $max to the largest. In your case, you would set $min to 0 and $max to 9. This will give you 4 values that you can use to index your pages.
Post Reply

Return to “Developers Discussion”