views:

186

answers:

3

Anyone know how to get a random set of lines from a text file?

I want to get a set of 3 lines with <br> on the front of each and display them through html.

example:

set 1
<br>Hi
<br>what's your name
<br>goodbye

set 2
<br>stack
<br>overflow
<br>hi there

set 3,4,5....

Choose one random set and display it. The sets of lines would be stored in a text file.

Thanks a lot!

+1  A: 

Put all the possibilities in an array and then us array_rand() I guess.

Devin Ceartas
any ideas on how to do that specifically? I know very little PHP.
Jack
The online php documentation is a good place to start: http://php.net/manual/en/function.array-rand.php
Scuzzy
A: 

You can use array_chunk to create a single array comprised of sub-arrays of a specified size:

$fileArr = file('someFile.txt');

// randomize the array
$lines = array_rand($fileArr, 3);

// break it into a single array comprised of arrays of three elements
$chunks = array_chunk($lines, 3);

// read out values of each sub-array
foreach($chunks as $chunk) {
    echo $chunk[0] . '<br />';
    echo $chunk[1] . '<br />';
    echo $chunk[2] . '<br />';
    echo '<br />';
}
karim79
A: 

If the chunks in the text file are always split by the blank line you can ready the file into a single string then split by \n\n. Then from there grab a random element from that array.

jerebear