0

I'm wondering what is the easiest/cleanest way to get an array of random values from an array in PHP. It's easy to get an array of random keys but it seems there's not function to get array of values straight away

The easiest way I found out is:

$tokens = ['foo', 'bar', '...'];
$randomValues = array_map(function($k) use ($tokens) {
    return $tokens[$k];
}, array_rand($tokens, rand(7, 20)))

This returns 7-20 random values from $tokens variable. However this looks ugly and is very unclear at first sight what it does.

3
  • 1
    since your code is actually working, this looks like a prime candidate to move to codereview.stackexchange.com Commented Apr 25, 2016 at 21:56
  • shuffle and then array_slice to get the number of values that you want Commented Apr 25, 2016 at 21:56
  • 1
    Are sure you aren't getting repeated values ? I would check if the value already exists in the new array. Commented Apr 25, 2016 at 21:58

2 Answers 2

2

If you don't want to modify your $tokens array, you could flip your randomly generated array keys and then use array_intersect_key. I think it's a little more readable than the array_map method, but I suppose that's fairly subjective.

$randomKeys = array_flip(array_rand($tokens, rand(7, 20)));
$randomValues = array_intersect_key($tokens, $randomKeys);

If you don't care if $tokens is modified, the shuffle\slice method seems very straightforward.

Sign up to request clarification or add additional context in comments.

Comments

1

Just shuffle and then slice a random number of elements:

shuffle($tokens);
$result = array_slice($tokens, 0, rand(7, 20));

If you don't want to modify the array then obviously just assign another variable and use that:

$temp = $tokens;

Comments

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.