Selecting a few unique, random array items by shuffling keys

Sunday, 15 April 2007 @ 20:42

MGeary helped me clean a complex function—containing many lines and loops—up into four concise lines by utilizing the shuffle function. I thought that I would posted it here in case it helps anyone else. I was trying to randomly select five unique items from a multi-dimensional array and although I had achieved the results I wanted, his suggetion allowed me to shorten my code considerably.

$howmany_want = 5;
$author_keys = array_keys($authors);
shuffle($author_keys);
$author_keys = array_slice($author_keys, 0, $howmany_want);

respond to post

You must be logged in to post a comment.

responses

  1. utahhomebook.info » Bobcats try to make it four wins in a row vs. Sixers2007/4/16 @ 0:11

    […] Selecting a few unique, random array items by shuffling keys […]

  2. andrix2007/5/21 @ 3:26

    nice

pages

categories

events

syndication

random members

Utah PHP Users Group

recent posts

recent comments

recent job announcements

search

administered by Anavi Design
colocated at Tier Four