Reputation: 13866
I have an array consisting of N>10 URLs. I want to randomly pick 10 of them and store them in another array. How can I achieve this? Is array_rand()
the way to go? If yes, then how do I ensure that there are no duplicities in the output array? Do I have to check the second array everytime a new element is added for existence?
// $firstArray is defined earlier
$secondArray = array();
array_push(array_rand($firstArray, 10));
This doesn't work unfortunately. I was thinking about using a for cycle for the array_push()
but I was just curious if array_rand()
can do that for me.
Thanks for advice!
Upvotes: 0
Views: 2257
Reputation: 36
If you use array_push like in the example code, the last index in your second array will contain the returned 10 indexes
Eg.
$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => d
[1] => e
[2] => f
)
)
I would use a while in this case and pick only one value at a time. Something like:
$stack = array();
while(count($stack)<10){
$item = array_rand($collection_of_urls);
if(!in_array($item)
array_push($stack, $item);
}
Upvotes: 1
Reputation: 4844
As people said there is a second argument in array_rand()
to pick how many random elements you want, always remember to read the Manual
//Lets pick 10 mammals
$mammals = array('dog', 'cat', 'pig', 'horse', 'bat', 'mouse', 'platypus', 'bear', 'donkey', 'deer', 'hog', 'duck');
$ten = array_rand(array_flip($mammals), 10);
//If what yo u really wanted is to append them to another array, let's say "animals":
$animals = array('fish', 'crab', 'whale', 'eagle');
$animals = array_merge($animals, array_rand(array_flip($mammals), 10));
Explanation
array_rand()
will return you the keys, so we can use array_flip()
here to reverse the keys => values positions before picking them, no need to loop through them again.
And using array_merge()
we merge them together, with no need to loop through the ten random elements to add them one by one, unless ... you want a specific order or other logic.
Upvotes: 2
Reputation: 76656
This can be done without array_rand()
. Use shuffle()
to shuffle the array elements and then use array_slice()
to get the first 10 items:
$secondArray = array();
shuffle($firstArray);
$secondArray = array_slice($firstArray, 0, 10);
Upvotes: 2
Reputation: 81
Not very optimized solution, but for small amounts of data it may suit:
$firstArray = array(1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9);
$secondArray = array();
$tmp = array_unique($firstArray);
shuffle($tmp);
$secondArray += array_slice($tmp,0, 10);
Upvotes: 1
Reputation: 10061
this simple
$rand_keys = array_rand($input, 10);
print_r($rand_keys);
Upvotes: 0
Reputation: 336
array_rand returns keys so
$randKeys = array_rand($firstArray, 10);
foreach($randKeys as $key)
$secondArray[] = $firstArray[$key]
Upvotes: 3