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.
You could shuffle
the array and then pick the first ten elements with array_slice
:
shuffle($array);
$tenRandomElements = array_slice($array, 0, 10);
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With