1

I have a text file with a list of sentences on each line. Currently, I just randomize the lines but have many duplicates show up. How can I get these lines into an array and then show them all randomly but don't show a sentence again until all sentences have been shown. Basically, I need to loop through the array one full time before I show the quotes over again.

<?php 
 $list = file('list.txt');
 shuffle($list);
 echo $list[0];
?>
Trey Copeland
  • 3,387
  • 7
  • 29
  • 46
  • Show to whom? In what context? Loop through for a single user, or across all users? – Problematic Jul 29 '11 at 21:10
  • It's just a single text file with a sentence on each line. It should echo that sentence. – Trey Copeland Jul 29 '11 at 21:11
  • And you want to show one line per request until all sentences have been displayed, then randomize the list and start again? I'm still struggling a bit to understand exactly what you're looking for. – Problematic Jul 29 '11 at 21:13
  • Yes, show one line per request. Then randomize list and start again but don't show the previous lines in the array until all lines have been shown. – Trey Copeland Jul 29 '11 at 21:15
  • Check out http://stackoverflow.com/questions/6471462/get-random-value-from-a-php-array-but-make-it-unique/6471544#6471544 – Steve Robbins Jul 29 '11 at 21:20

3 Answers3

1

Shuffle doesn't create duplicates in your array, so this code just works fine:

<?php
$list = array(1,2,3,4,5,6);
shuffle($list);
print_r($list);
?>

Array
(
    [0] => 2
    [1] => 3
    [2] => 6
    [3] => 4
    [4] => 1
    [5] => 5
)

That means you have duplicate lines in your file. If you want to get an array with unique values use this: $unique = array_unique($list);

<?php
$list = array(1,1,2,2,3,3);
$unique = array_unique($list);
shuffle($unique);
print_r($unique);
?>


Array
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Caner
  • 57,267
  • 35
  • 174
  • 180
0

One easy way to do this would be instead of shuffling the array every time, just pick a random index. Then, store this index in a list. By that, you can check upon the next function call if you have used this index already (if you store them in a sorted list, you can check that very fast, e.g. by using binary search). If the number of indexes equals the number of lines in your file, you can safely discard your list and start a new one, as all indexes have been used at that point of time.

Martin Matysiak
  • 3,356
  • 2
  • 17
  • 19
0

You can first remove duplicate lines and put the result into an array x.

Then pick one random element from array x, print it, and move it to a second (initially empty) array y. Repeat until array x is empty. Then you can start all over again moving elements from array y to array x.

Giorgio
  • 5,023
  • 6
  • 41
  • 71