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?
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:
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 usearray_combine
to turn those values into keys of another array.