caner taşdemir caner taşdemir - 1 year ago 92
PHP Question

php - How to show values in array randomly

I have an array with values,

$member[1] = "John";
$member[2] = "Mary";
$member[3] = "Berry";
$member[4] = "James";
$member[5] = "Lincoln";

I can show them randomly using

echo $member[rand(1,5)];
echo $member[rand(1,5)];
echo $member[rand(1,5)];
echo $member[rand(1,5)];
echo $member[rand(1,5)];

But this way, a member can show up twice or even more!
What is the correct and professional way to show them only once randomly ?

Answer Source

If you want to consume the entire array at random order use shuffle.


foreach($member as $memberName) {
    echo $memberName;

If you want to select one or more elements from the array at random use array_rand.

Let's say you want to select 3 members from the array at random, with the guarantee that you will never pick the same array value twice.

foreach(array_rand($member, 3) as $key) {
    echo $member[$key];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download