Simple helper function which returns a random subset of an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*-------------------------------------------------------------------------------------*\
  Function:    get_random_subset
  Description: accepts an array as an argument, and returns a random subset of its
                   elements. May be empty, or the same set.
  Parameters:  $set - the set of items
               $num - the number of items in the set to return
\*-------------------------------------------------------------------------------------*/

function get_random_subset($set, $num)
{
  // check $num is no greater than the total set
  if ($num > count($set))
    $num = count($set);

  shuffle($set);
  return array_slice($set, 0, $num);
}