Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select 10 random things from a list in PHP?

Tags:

arrays

php

random

I know how to select one random item from an array, but how about ten random items from an array of, say, twenty items? (In PHP.)

What makes it a little more complicated is that each item actually has two parts: a filename, and a description. Basically, it's for a webpage that will display ten random images each time you reload. The actual format of this data doesn't really matter, although it's simple enough that I'd prefer to contain it in flat-text or even hard code it rather than set up a database. (It's also not meant to change often.)

Bonus question, not sure if I'm going to do this just yet - but how would you weight the entries, such that certain items always get picked, or at least more frequently than others?

Thanks.

like image 325
saikofish Avatar asked Aug 07 '09 12:08

saikofish


2 Answers

You could shuffle the array and then pick the first ten elements with array_slice:

shuffle($array);
$tenRandomElements = array_slice($array, 0, 10);
like image 144
Gumbo Avatar answered Nov 07 '22 05:11

Gumbo


How to select one or more random items from an array in php: http://us3.php.net/manual/en/function.array-rand.php

How to do random weighted elements:
http://20bits.com/articles/random-weighted-elements-in-php/

like image 23
Mr. Smith Avatar answered Nov 07 '22 05:11

Mr. Smith