views:

87

answers:

2

Hey, I have a function which calls a users associated users from a table. The function then uses the rand(); function to chose from the array 5 randomly selected userID's however!...

In the case where a user doesnt have many associated users but above the min (if below the 5 it just returns the array as it is) then it gives bad results due to repeat rand numbers...

How can overcome this or exclude a previously selected rand number from the next rand(); function call.

Here is the section of code doing the work. Bare in mind this must be highly efficient as this script is used everywhere.

$size = sizeof($users)-1;
    $nusers[0] = $users[rand(0,$size)];
    $nusers[1] = $users[rand(0,$size)];
    $nusers[2] = $users[rand(0,$size)];
    $nusers[3] = $users[rand(0,$size)];
    $nusers[4] = $users[rand(0,$size)];

    return $nusers;

Thanks in advance! Stefan

+1  A: 

If you just want to shuffle your array items, use shuffle:

shuffle($users);
return $users;

Note that shuffle requires pass by reference. So you need to pass a variable that’s is then shuffled.

Gumbo
+3  A: 

The simplest way is to use array_rand():

$users = range(3, 10); // this is just example data
$nusers = array_rand($users, 5); // pick 5 unique KEYS from $users

foreach ($nusers as $key => $value)
{
  $nusers[$key] = $nusers[$value]; // replace keys with actual values
}

echo '<pre>';
print_r($nusers);
echo '</pre>';

PS: Read this to know why you should use mt_rand() instead of rand().

Alix Axel
For whatever reason, I can't load that link.
R. Bemrose
@R. Bemrose: http://www.boallen.com/random-numbers.html covers the same subject.
Alix Axel