Randomly pick element in array then remove from the array

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

    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 );
    
    0 讨论(0)
  • 2020-12-30 03:51

    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";
    }
    ?>
    
    0 讨论(0)
  • 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.

    <?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);
    
    0 讨论(0)
  • 2020-12-30 03:59

    You could also use array_slice

    $ran_Num = array_rand($phrases);
    $ran_Phrase = array_slice($phrases, $ran_Num, 1);
    
    0 讨论(0)
  • 2020-12-30 04:01

    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;
    }
    
    0 讨论(0)
提交回复
热议问题