Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly pick element in array then remove from the array

Tags:

arrays

php

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.

http://codepad.org/11l0nStX

<?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?

like image 898
ttmt Avatar asked Jun 14 '13 14:06

ttmt


People also ask

How do you remove random items from an array?

We are required to create a function removeRandom() that takes in the array and recursively removes one random item from the array and simultaneously printing it until the array contains items. This can be done through creating a random number using Math. random() and removing the item at that index using Array.

How do you remove an element from an array array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an element from an array with value?

The splice() function adds or removes an item from an array using the index. To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.

Can we access the array elements randomly?

The Math. floor() returns the nearest integer value generated by Math. random() . This random index is then used to access a random array element.


1 Answers

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;
}
like image 133
Mārtiņš Briedis Avatar answered Oct 31 '22 07:10

Mārtiņš Briedis