Hold on... This isn't EnnuiDesign.com — What Gives?
It's been a long time coming, but Jason Lengstorf, formerly of Ennui Design, has expanded his team to include Drew Douglass, Rob MacKay, Henry Moran, and Tom Sturge.
It didn't feel right to keep the same name, so we decided to continue on as Copter Labs. You can expect the same great content under this new name!
Generate a Random Subset of Array Elements
I ran into an interesting problem while developing a new blogging system recently where I needed to generate a subset of array elements in random order.
A random subset of elements is useful for displaying a sampling of entries that changes with every page load, such as four random blog entries, a photo gallery that stays interesting even if new photos aren't uploaded, or, if you want to use a sweet content slider, you could show random portfolio or blog entry previews and keep your slider fresh.
Defining the Problem
The Array
First things first, we need to know what we're dealing with. For the purpose of this example, we'll be using a multi-dimensional array that looks something like this:
$entries = array( array( 'title' => 'Entry One', 'author' => 'Jason Lengstorf', 'date' => 'April 8, 2009' ), array( 'title' => 'Entry Two', 'author' => 'Jason Lengstorf', 'date' => 'April 9, 2009' ), array( 'title' => 'Entry Three', 'author' => 'Jason Lengstorf', 'date' => 'April 10, 2009' ), array( 'title' => 'Entry Four', 'author' => 'Jason Lengstorf', 'date' => 'April 11, 2009' ), array( 'title' => 'Entry Five', 'author' => 'Jason Lengstorf', 'date' => 'April 12, 2009' ), array( 'title' => 'Entry Six', 'author' => 'Jason Lengstorf', 'date' => 'April 13, 2009' ), array( 'title' => 'Entry Seven', 'author' => 'Jason Lengstorf', 'date' => 'April 14, 2009' ), array( 'title' => 'Entry Eight', 'author' => 'Jason Lengstorf', 'date' => 'April 15, 2009' ) );
This is an array that's similar to the kind that would be returned from a database query. In it, we have eight entries, each of which contains another array that holds the title, author, and date of the entry (I omitted the entry itself in the interest of brevity).
The Goal
Our goal is to create a subset of four entries in random order, and to have the subset change every time the page is loaded (i.e. entries 4, 2, 8, and 7 are loaded the first time, then entries 3, 8, 1, and 6, and so on).
Writing the Code
Our array will be processed in a function called getRandomSubset(), which will accept two arguments: the array ($entries), and the number of entries to be returned in the subset ($number).
function getRandomSubset($entries, $number)
{
// Process entries here...
}
PHP provides a ton of array handling functions that simplify the process of manipulating arrays. One of the available functions is called array_rand(), which returns a random assortment of array keys (as a variable if only one element is returned, or as an array if two or more are returned).
We're able to pass two arguments to array_rand(): the first is required and contains the array from which we need random elements, and the second is an optional specifier that allows us to decide how many elements need to be returned (if not set, this defaults to 1).
Because array_rand() only returns the array element keys, we'll need to do a little more coding to get the actual element values. To do this, we'll create an empty array called $randList that will store our random array elements, then run a loop with the random keys to add each element to the array using another array function called array_push(), which adds a value to the end of an array.
function getRandomSubset($entries, $n)
{
// Initiate the variable
$randList = array();
// Pull the desired number of entry keys at random
$keys = array_rand($entries, $n);
// Loop through the keys
foreach($keys as $key) {
// Add the value to end of the return array
array_push($randList, $entries[$key]);
}
return $randList;
}
To test this code, add the following snippet to a test page. NOTE: The <pre> tags are used to enhance the readability of output generated by print_r().
echo '<pre>'; print_r(getRandomSubset($entries, 2)); echo '</pre>';
Running the code will output something similar to the following:
Array
(
[0] => Array
(
[title] => Entry Four
[author] => Jason Lengstorf
[date] => April 11, 2009
)
[1] => Array
(
[title] => Entry Six
[author] => Jason Lengstorf
[date] => April 13, 2009
)
)
The Problem with Too Few Entries
One problem that exists in our code is that a warning will be issued and no values returned if more entries are requested than available in our entry array. If we call echo getRandomSubset($entries, 9);, an error similar to the following will be output:
Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /Applications/xampp/xamppfiles/htdocs/test.php on line 75
Warning: Invalid argument supplied for foreach() in /Applications/xampp/xamppfiles/htdocs/test.php on line 78
Array ( )
Solving the Problem
To correct this issue, we need to add a check that ensures the number of entries requested does not exceed the number supplied. If too many entries are requested, we then change the number of requested entries to match the number of available entries, thus avoiding the error and outputting as many entries as possible.
function getRandomSubset($entries, $n)
{
/*
* If $n is greater than the number of entries,
* reset it to be the number of entries available.
*/
$n = (count($entries)<$n) ? count($entries) : $n;
// Initiate the variable
$randList = array();
// Pull the desired number of entry keys at random
$keys = array_rand($entries, $n);
// Loop through the keys
foreach($keys as $key) {
// Add the value to end of the return array
array_push($randList, $entries[$key]);
}
return $randList;
}
Testing the function should now always result in a subset of the desired length with no duplicate entries. The subset can then be passed to the formatting function of your choice to handle formatting.
Summary
Getting comfortable with the intricacies of loops and arrays can have a huge impact on the cleanliness and readability of your code. What tricks do you have up your sleeve? Let me know in the comments!
Other Notes
I had an article run on NETTUTS called Add Power to Your PHP With Multi-Tiered Applications. It covers what I consider to be best practices while writing code, so I'd love to hear your thoughts on it.
Also, just as a general note, thanks for reading! I really appreciate your comments and support, and I hope to keep supplying you with all the PHP geekery you can handle!
Comments.
Why didn't you use mt_rand()? I would use it if I had to write something like this.
Frank 8:40am Apr 23, 2009 permalink | flag
@Frank:
In this case, because it doesn't really matter how random the entries are, I opted for the built-in function to pull random array keys.
I had originally written another way to do this that used mt_rand(), but it was more complicated.
However, I'd love to see your take on the function. Feel free to post your version in the comments!
Jason Lengstorf 10:13am Apr 23, 2009 permalink | flag
@Jason Lengstorf:
Oh, I overlooked the array_rand() function. I think that's a better solution than mt_rand(). :)
But I would do something like this: http://pastebin.com/f271df581
Frank 11:13am Apr 23, 2009 permalink | flag
@Frank:
That's almost exactly what my original solution was, except I skipped the while(true) by leaving the third expression in the for loop empty:
function get_random_subset($array, $n)
{
$random_items = $random_keys = array();
$item_count = count($array);
$n = $n > $item_count ? $item_count : $n;
for ($x=0; $x < $n; ) {
$r = mt_rand(0, $item_count-1);
if (!in_array($random_items, $array[$r])) {
$random_items[] = $array[$r];
++$x;
}
}
return $random_items;
}
Thanks for your input!
Jason Lengstorf 11:29am Apr 23, 2009 permalink | flag
Also came across this problem once, but I wanted to preserve the keys of the original array, so I made this oneliner:
function array_rsubset($array, $count) {
return array_intersect_keys($array, array_flip(array_rand($array, $count)));
}
Rudolf Leermakers 12:22pm Apr 23, 2009 permalink | flag
@Rudolf Leermakers:
That function is brilliant! However, the entries are always in ascending order, so you'd have to write another function to shuffle them.
Also, array_intersect_keys() isn't actually a function; I think you were looking for array_intersect_key().
Thanks!
Jason Lengstorf 1:25pm Apr 23, 2009 permalink | flag
@Jason
Yeah, the intersect_keys() was a typo, I didn't actually copy-paste it, didn't take the time to find where I stored it :)
And for the order-problem, that has to do with the order of the original array, you could shuffle that, or shuffle the end-result in the same line, but I totally missed that problem before, thanks for mentioning it!
Rudolf Leermakers 1:47pm Apr 23, 2009 permalink | flag
Nice to be visiting your blog again Herve Leger, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article Herve Leger Dresses. Thanks, great share.
herve leger 10:04pm Nov 27, 2011 permalink | flag
Choosing amongst a myriad of large things was not in the least my speciality, so when I had to preferable my exceed ten computer games, I was definitely faced with a challenge. After some pensive (and I mean surely judgement sometimes non-standard due to), this is the file of games that I know are worthy to be mentioned in my top ten computer games article.
Lately, many people the time of one's life playing video games on consoles such as Ps3 and Xbox 360 because of alluring games and the ease of use. Many consoles involve with a outstrip graphics card that allows in the service of deeper gaming experience. So does this wealth the aim of PC gaming era? Obviously not. Computers gave creation to the video field industry. Unequal to the consoles, computers oblige been almost for more than 25 years. All the years of experiences unite up to recovered games and it conveys the essence that pc gaming on be about in the interest of a hanker time. Still today, computer gaming leads the gaming hustle because most gamers are PC gamers.
3) Discharge’s start with some Dress up Games browned off birds and some unripe pigs.
I cannot envisage my best ten computer games shopping list without this game. Ireful Birds is a simple casual occupation, but who am I kidding? You perhaps recognize what Fuming Birds is. And if you aren’t wiped out bored with of having played it on your android phone, iPhone, tablets, iPad, roku etc, you can also play the darn thing on your computer!
2) StarCraft
Is it ill-use that more than half of my top ten computer games consist of tactics games? The unmodified cannot be said on the side of consoles. PC games contradict because you indeed secure to ‘characterize as’ and be sharp-witted, specially in this meeting; Star Craft. Individual aspects of the meeting such as motivation, technology, biology, and a brilliant fable prevail upon this pastime song of the most ordinary verified span procedure game. This group of galvanizing and addicting gamble cannot be develop in consoles platform. The on the other hand habit to know what I am talking yon is to vie with this game, you are undeviating to understand then!
Computer games are the superlative games in the in style gaming era. Console games are capable too, but really not as enjoyable as ones I take on on computer in my opinion. My heel of outstrip ten computer games may switch in the tomorrow's as PC gaming persistence is immense and fitting for trustworthy, it force mould for decades to come.
Rendsinge 8:55am Jan 3, 2012 permalink | flag
Your posts are so helpful and detailed. The links you feature are also very useful too.
junior bridesmaid dresses 12:01am Feb 8, 2012 permalink | flag
Nice artwork. So much creative. Can you please tell me which tool you use to create these type of amazing art designs.love
knockoff handbags 6:43am Feb 22, 2012 permalink | flag
124253141
RQTBXT216 11:42am Mar 22, 2012 permalink | flag
payday loan Zone is a payday loan lending and is not a payday loan lender.
Bityblue 11:07pm Mar 24, 2012 permalink | flag
Moothedrode 2:14pm Mar 30, 2012 permalink | flag
vprx
vprx pills
http://www.vprxpills.com - vprx pills
buy penis pills
Neissesheaphy 12:52am Apr 9, 2012 permalink | flag
These things! Bastard...
swords shop 7:31pm Apr 9, 2012 permalink | flag
Hello
I want to make sure her daughter is not schizophrenia Coq10 erectile dysfunction I want to get married Apple cider vinegar erectile dysfunction I want to lose weight Impotence ring kit
Go to the guests
seniawamma 1:53pm Apr 13, 2012 permalink | flag
Exchange for many cost-conscious travellers, the search seeing that the lowest airfares forms the core of their travel planning efforts. Flights are often among the most costly components in travellers' furlough budgets, and the savings enjoyed on those who successfully reserve low-cost flights can be allocated to other aspects of their furlough expenditure. For precedent, their accommodation and pageant budgets may be supplemented about such savings, making inasmuch as a more enjoyable holiday experience.
Airlines use complex algorithms darmowe typy to ascertain the airfares of unusual flights. Travellers equipped with a vital sagacity of these algorithms can power this expertise to their advantage past verdict the cheapest airfares when making cloud bookings. In inexact, the algorithms employed beside airlines are based on the principles of supply and demand. Airlines steal into account a tons of factors, the most weighty of which are the dates and times of detailed flights and the amount of behest and struggle this juncture in the retail within which the flight routes in doubt fall.
dobrzetypuje 12:32am Apr 17, 2012 permalink | flag
We're able to pass two arguments to array_rand(): the first is required and contains the array from which we need random elements, and the second is an optional specifier that allows us to decide how many elements need to be returned (if not set, this defaults to 1).
jersey from china 2:45am Apr 18, 2012 permalink | flag
Tamydedge 1:03pm Apr 21, 2012 permalink | flag
It's quite interesting.I will look around for
Ken Griffey Shoes 7:21am Apr 24, 2012 permalink | flag
Designer handbags assure a really unique style statement. They're regarded as among the coolest add-ons in the current time. Designer handbags are without a doubt good quality handbags that exude elegance and class.
To many women, handbags are not only regarded as functional products which help them carry their necessary possessions but additionally certainly one of their significant preferences in succeeding the very best fashion style they most desire. It's the item that girls always remember to hold together once they occur to venture out unconditionally. It's without a doubt the most crucial add-ons for ladies of various age range. They've been very important ensemble for contemporary women's fashion. Each lady desires to demonstrate the coolest and gorgeous handbag she's. They're wanting for any stylish and trendy handbag, that is comfortable in addition to simple to use.
You will find a lot of types of designer handbags for girls, probably the most luxuries and stylish are Hermes handbags.
Hermes bags frequently are available in traditional, sophisticated and lavish look. They've been extremely popular and favorite by women due to their fame and amazing features and sturdy quality. Hermes handbags assure a classy elegant look that's perfect with any woman's wardrobe.
The Hermes Kelly is definitely an legendary bag, however with its structured shape and usual more compact dimensions, it gives a really formal vibe for your clothes. When Hermes sent the Jypsiere for his or her Fall 2008 collection, everybody who was simply wanting a far more casual everyday Kelly were excited. The Hermes Jypsiere reinterpreted the Hermes Kelly by altering it right into a messenger bag which will spend time at the stylish. The slightly rounded bottom and adjustable shoulder strap reinvented the Kelly in ways many people didn't expect.
Messenger bags typically incorporate features which make them particularly appropriate for cycling, for example fixtures making it simple to adjust the shoulder strap, quick release buckles, a variable hinged buckle, and a chance to attach a number of add-ons, for example lights, phone holsters, or U-locks. A really prominent feature of messenger bags would be the connectors, because this helps you to carry the bag easily. Contemporary backing straps assistance to avoid the bag from shifting while riding. The messenger bag looks very sleek instead of a backpack, also it handles to obtain all of the essentials to college and back.
Really the modification was quiet welcomed by many people. There's something so elegant in regards to a typically chic messenger style bag. All the particulars that Hermes is renowned for show about this bag, however the overall appeal changes drastically. The Jypsiere isn't just an uptown-ladies-who-lunch-bag, it's a a lot more functional everyday bag.
astorovot 9:22pm May 2, 2012 permalink | flag
Category 2 Tickets. price £400 each
Tickets sold together ( 4X )
Excellent view , tickets seating ( next to each other)
longside area
Allianz Arena, Munich on Saturday 19 May 2012
Contact:
+442036275973
[email protected]
fueroiprowNer 7:52pm May 4, 2012 permalink | flag
Category 2 Tickets. price £400 each
Tickets sold together ( 4X )
Excellent view , tickets seating ( next to each other)
longside area
Allianz Arena, Munich on Saturday 19 May 2012
Contact:
+442036275973
[email protected]
fueroiprowNer 7:53pm May 4, 2012 permalink | flag
European Cup Ukraine 2012 + 2011+2012+2013
Dear friends
We think that Great Britain should reward us fans with more attractiv football!
Please go to see our litte survey
micropolll.com/bmkh/ho4mt
The poll is supported by 2012 Sponsor KRAFTFoods
schönheitsblog
operative Brustvergrößerung Kosten
tortenfisch98 By the way: Messi is the best player of the World Cup
football 2013+2014
nasenoperation 8:19pm May 4, 2012 permalink | flag
Your Baby Can Read can be an early language development technique for infants and little ones. Based on the analysis of Dr. Robert Titzer, the DVDs employ whole reading and a few phonics to help little ones learn language patterns while in an optimal time whenever their brains are developing rapidly and are also intensely focused on getting your hands on language patterns.
According to Dr. Titzer, babies can learn your patterns of written language in the same way naturally and easily as they learn the patterns involving spoken language. Often though, babies are not encountered with enough written language just for this learning to occur. The Your Baby Can Read! system contains five DVDs which might be focused on helping babies and kids approximately five years old learn how to read by giving these individuals a multi-sensory experience with heavy contact with print.
I've been seeing the infomercial with the my Baby Can Read program and 'm very intrigued! But I'm never the kind to just jump for the phone and order what intrigues me. I did some quick research and read up on some reviews - plus the result is mixed.
While it's great, and proven, that the children will often have positive results, "reading" words and recognizing what they may be, but then I wonder whether or not it's actual reading or simply memorization. And even I have learned about The Hurried Child through David Elkin. I've never actually read the book, but I've learned about the results/outcome of his book in several courses throughout my education and learning, K-12 and Uni.
The Your Baby Can Read program will be based upon the fact that your baby uses associations to study new things. It will show them what the term looks like, show them a picture of the word in action, and let the child hear the sounds in the word in action also. So using the senses of sight and noise, your child is being entertained by seeing all of the pieces come together.
Ever wonder why kids can learn a fresh language MUCH faster than you are able to? Their brains are just geared to learning language greater than ours at that age group, and there's no purpose to stifle that. My kids are capable of excel in their colleges because we started at such an early age, and this makes fewer severe headaches for me in trying to help them with his or her homework.
I have seen the Your Baby Can Read infomercials hundreds of times, but I was anxious to utilize it myself with my own toddler and discover the results.
I must admit, the Early Learning Workshop DVD that is included with the program, which you are encouraged to view before beginning this program using your child, is VERY overwhelming. It is long and unless you have a great attention span (I not) you may perhaps skip the DVD, read the Parents guide and just get started.
Preryvolavili 11:25am May 8, 2012 permalink | flag
Join In.
Have something to say? By all means, speak up!
But first, a few rules:
Happy commenting!