Reputation: 445
As far as I know array_rand()
can only grab a radnom array from an array like this:
$array = array( 'apple', 'orange', 'banana' );
$two_random_items = array_rand( $array , 2 ); // outputs i.e. orange and banana
But how can I grab 2 random items but with the key value array? Like this?
$array = array( '0' => 'apple', '1' => 'orange', '2' => 'banana' );
$rand_keys = array_rand($array, 2);
$rand_values = array();
foreach ($rand_keys as $key) {
$rand_values[] .= $array[$key];
}
That's probably not the right way and it's a lot of code.
I have a big array this is just an example and I need to grab 1000+ or more items randomly from the parent array and put them in a new array, keys can be reset, this is not important. The value part has to stay the same, of course.
Is there a better way how to achieve this?
Upvotes: 1
Views: 221
Reputation: 2706
First, this line: $rand_values[] .= $array[$key];
is wrong. The .=
operator is to join strings, to add a value to the end of the array, you just need $rand_values[] = $array[$key];
.
If you don't care about the keys, just use array_values
function to "dump" the keys.
$array = array('a' => 'orange', 'c' => 'banana', 'b' => 'peach');
$two_random_items = array_rand(array_values($array) , 2 );
array_values will strip down the keys, and will return an array with the values (the keys will become 0, 1, 2...)
Upvotes: 0
Reputation: 78994
Just shuffle and slice 2:
shuffle($array);
$rand_values = array_slice($array, 0, 2);
Upvotes: 2