Reputation: 4124
I have an array of values.
array = ["A", "B", "C"];
I want to randomly select an item, do something with it, then remove it from the array. Go back and get another item, etc.. etc..
So that I get:
$item = "B";
array = ["A","C"];
$item = "C";
array = ["A"];
$item = "A";
array =[];
I know Ruby has a array.delete_at()
function which would work great if i was using Ruby. Is there a function similar to that in just generic PHP?
Upvotes: 0
Views: 722
Reputation: 78994
Randomize with shuffle()
and then pop one off the end, or shift off of the beginning with array_shift()
, doesn't matter:
shuffle($array); // you only need to do this once
$item = array_pop($array);
Similar to the Ruby you show would be to get a random key and use it to get the value, then use it to unset()
that element:
$item = $array[$key=array_rand($array)];
unset($array[$key]);
Upvotes: 3
Reputation: 121
There are two possible answers:
If you don't care about order of elements that will be left in the array, for example you will pick all elements anyway:
$array = ["A", "B", "C"];
shuffle($array);
while (!empty($array)) {
$randomElement = array_pop($array);
var_dump($randomElement);
}
If you don't want to pick all element, only few. You can remove just elements that you pick, leaving other in the same order:
$array = ["A", "B", "C"];
while (!empty($array)) {
$randomKey = array_rand($array);
$randomElement = $array[$randomKey];
unset($array[$randomKey]);
var_dump($randomElement);
}
Upvotes: 1