caner taşdemir caner taşdemir - 2 months ago 12
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

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

shuffle($member);

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];
}
Comments