Randomly pick element in array then remove from the array

后端 未结 5 787
鱼传尺愫
鱼传尺愫 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:58

    Place the selected values an a new array then check if it exists in the new array if not add it.

     ($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);
    

提交回复
热议问题