Grg
Grg

Reputation: 13

Randomly pick element in array then remove from the loop

I'm attempting to make a program along the same lines as this. I am trying to randomely select an element from the array, display it, and then remove it from the array. However, the element is not displaying.

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

    }

?>

Upvotes: 1

Views: 65

Answers (1)

Ethan
Ethan

Reputation: 446

<?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');
for($i=0; $i<16; $i++){ 
    $ran_Num = array_rand($phrases);
    $ran_Phrase = $phrases[$ran_Num];
    echo $ran_Phrase."<br>";      
    echo count($phrases)."<br>";
    unset($phrases[$ran_Num]);
}
?>

Brought the array outside the loop (since if it's inside, it'll always reset to 16 items).
Replaced $phrases[$ran_Phrase] to $phrases[$ran_Num] because we unset index.

EDIT:

PHPFiddle - Demo: http://phpfiddle.org/main/code/pw2f-qrp3

Upvotes: 1

Related Questions