I have an array of phrases. I'd like to randomly pick phrases from the array in a loop. I don't want to pick the same phrase more then once in the loop. I thought I could randomly pick the phrase and then delete it before the next loop.
http://codepad.org/11l0nStX
<?php
for ($i=0; $i<16; $i++) {
$phrases = array(
'Hello Sailor', 'Acid Test', 'Bear Garden', 'Botch A Job',
'Dark Horse', 'In The Red', 'Man Up', 'Pan Out',
'Quid Pro Quo', 'Rub It In', 'Turncoat', 'Yes Man',
'All Wet', 'Bag Lady', 'Bean Feast', 'Big Wig',
);
$ran_Num = array_rand($phrases);
$ran_Phrase = $phrases[$ran_Num];
unset($phrases[$ran_Phrase]);
echo $ran_Phrase . "\r\n";
echo count($phrases) . "\r\n";
}
Is it possible to randomly pick a different phrase from the array on each loop?
We are required to create a function removeRandom() that takes in the array and recursively removes one random item from the array and simultaneously printing it until the array contains items. This can be done through creating a random number using Math. random() and removing the item at that index using Array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
The splice() function adds or removes an item from an array using the index. To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.
The Math. floor() returns the nearest integer value generated by Math. random() . This random index is then used to access a random array element.
Shuffle the array in random order, and just pop the last element off.
$array = [...];
shuffle($array);
while($element = array_pop($array)){
echo 'Random element:' . $element;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With