Randomly pick element in array then remove from the array

后端 未结 5 786
鱼传尺愫
鱼传尺愫 2020-12-30 03:06

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

5条回答
  •  鱼传尺愫
    2020-12-30 03:51

    The other answers here work, but I want to address your code.

    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";
    }
    ?>
    

提交回复
热议问题