1

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 ?

1
  • 2
    shuffle($members); foreach($members as $member){ echo $member; } Shuffle will randomize the order of elements in an array: Shuffle() Commented Sep 26, 2016 at 3:18

3 Answers 3

1

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, I was just using the OPs variable name for consistency, but I did use $members in the second example instead of $member. Thanks.
1

Use shuffle()

$shuffle($member);

http://php.net/manual/en/function.shuffle.php

Comments

1

Another choice,

$random_keys=array_rand($member,count($member));
echo $member[$random_keys[0]];
echo $member[$random_keys[1]];
echo $member[$random_keys[2]];
echo $member[$random_keys[3]];
echo $member[$random_keys[4]];

3 Comments

Note this will approach will give you identical results to the order of the elements in $member, because array_rand gives you random selection, not random distribution. So when you want to consume the entire array in random order it's better to just use shuffle, but if you want limited random selection and not random distribution, array_rand works fine. Also, you're using echo $a[[$random_keys[0]] when it should be echo $member[$random_keys[0]].
@Sherif Thank you for your comment. You are right... If we want to arrange entire array in random order it's better to just use shuffle. We can use array_rand when we want to limited random selection.
It doesn't have to be limited. I'm just pointing out it's random selection and not random distribution. i.e. you could shuffle($random_keys) if you wanted. I may have been a bit ambiguous there with my wording. By limited I mean that array_rand() limits selection to the set of available keys. Such that you will never get the same key twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.