Rand (); with an exception and an already randomly generated number ..?

I have a function that calls users linked to users from a table. The function then uses rand (); a function to select from an array of 5 randomly selected user IDs, however! ...

In case the user doesn't have many associated users but is above the minimum (if below 5 it just returns the array as it is) then it gives bad results due to repeated rand numbers ...

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

Here's a section of the code doing the job. It doesn't matter that it should be very 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! Stephen

+2


a source to share


2 answers


The easiest 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 find out why you should use mt_rand()

instead rand()

.

+3


a source


If you just want to shuffle the elements of an array, use shuffle

:

shuffle($users);
return $users;

      



Please note that you shuffle

need to follow the link. Therefore, you need to pass in a variable, which is then shuffled.

+1


a source







All Articles