1

I wanted to pull an arbitrary number of random elements from an array in php. I see that the array_rand() function pulls an arbitrary number of random keys from an array. All the examples I found online showed then using a key reference to get the actual values from the array, e.g.

$random_elements = array();
$random_keys = array_rand($source_array);
foreach ( $random_keys as $random_key ) {
  $random_elements[] = $source_array[$random_key];
}

That seemed cumbersome to me; I was thinking I could do it more concisely. I would need either a function that plain-out returned random elements, instead of keys, or one that could convert keys to elements, so I could do something like this:

$random_elements = keys_to_elements(array_rand($source_array, $number, $source_array));

But I didn't find any such function(s) in the manual nor in googling. Am I overlooking the obvious?

4
  • 1
    What's wrong with writing your own function for it? Commented Jan 19, 2012 at 18:22
  • Nothing's wrong per se; I was just thinking that I had to be re-inventing the wheel. Commented Jan 19, 2012 at 18:25
  • I don't think you are overlooking anything. If you want to be able to do it in one line, write a function that will help you do so. Commented Jan 19, 2012 at 18:26
  • @llama if you post that as an answer I will upvote and accept it :) Commented Jan 19, 2012 at 18:27

3 Answers 3

2

What about usung array_flip? Just came to my mind:

$random_elements =  array_rand(array_flip($source_array), 3);

First we flip the array making its values become keys, and then use array_rand.

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

Comments

1

An alternate solution would be to shuffle the array and return a slice from the start of it.

Or, if you don't want to alter the array, you could do:

array_intersect_key($source_array, array_combine(
    array_rand($source_array, $number), range(1, $number)));

This is a bit hacky because array_intersect can work on keys or values, but not selecting keys from one array that match values in another. So, I need to use array_combine to turn those values into keys of another array.

Comments

0

You could do something like this, not tested!!!

array_walk(array_rand($array, 2), create_function('&$value,$key', '$value = '.$array[$value].';'));

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.