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
You could also use array_rand and array_splice
$array = 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');
$el = array_rand($array);
$dat = $array[$el];
array_splice($array, $el, 1 );
The other answers here work, but I want to address your code.
<?php
I pulled the definition of $phrases
outside of the loop. By setting it inside the loop, it was being reset every time and that's no good.
$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');
I don't like counting, so I let the computer do it.
for($i=0,$n=count($phrases); $i<$n; $i++){
$ran_Num = array_rand($phrases);
$ran_Phrase = $phrases[$ran_Num];
When you unset on an array, the value that goes inside the square brackets should be the index of the array element you want to remove, not the value element itself. The variable inside the brackets has been changed from $ran_Phrase
to ran_Num
unset($phrases[$ran_Num]);
echo $ran_Phrase."\r\n";
echo count($phrases)."\r\n";
}
?>
Place the selected values an a new array then check if it exists in the new array if not add it.
<?php
$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');
$default = 16;
if($default > ($c = count($phrases))) $default = $c;
$keys = array_rand($phrases, $default);
$newPhrases = array();
foreach($keys as $key){
if(!isset($newPhrases[$key])){
$newPhrases[$key] = $phrases[$key];
}
}
print_r($newPhrases);
You could also use array_slice
$ran_Num = array_rand($phrases);
$ran_Phrase = array_slice($phrases, $ran_Num, 1);
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;
}