Jump to content

Randomly pick element in array then remove from the array


ttmt_73

Recommended Posts

Hi all

 

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 randomly pick the phrase and then delete it before the next loop.

 


 



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


 

Is it possible to randomly pick a different phrase from the array on each loop.
Link to comment
Share on other sites

It's generally easier to just randomize the array and then start take what you want off the top. Since you seem to be using all the array entries, just foreach the randomized array.

 

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

shuffle($phrases);
foreach ($phrases as $p){
  echo $p, '<br>';
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.