Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top