views:

78

answers:

3

How do you make a function read form a txt file and store random lines in a variable? It will be run over and over in a foreach loop. The language is PHP.

Im a new coder so I don't know things like this off the top of my head.

+4  A: 

One way to do it:

$contents = file('myfile.txt');
shuffle($contents);
array_splice($contents, 5);

var_dump($contents);
  1. Reads the whole file into an array
  2. Shuffles the array
  3. Cuts the array off after 5 elements

Now you have an array of 5 randomly chosen strings.

This method simple, but rather inefficient if the file is very big.

deceze
thanksyou rule
@user309716 upvote and accept
Moak
I think by "insufficient" you mean "inefficient". ;)
musicfreak
@musicfreak I think I do, too. :)
deceze
+2  A: 
// read the file
$file = file_get_contents( $path );

// convert to array of lines (assuming \n is delimiter)
$lines = explode( "\n" , $file );

// put lines in random order
shuffle( $lines );

// grab the first few lines or whatever you need
$random_lines = array_slice( $lines , 0 , 10 );
drawnonward
loading the file with `file` instead of `file_get_contents` saves you the `explode`.
Gordon
yes, file is a much better choice for this, especially with the FILE_IGNORE_NEW_LINES and possibly FILE_SKIP_EMPTY_LINES options.
drawnonward
+2  A: 
$file = file( $path );
shuffle( $file );
$random_lines = array_slice( $lines , 0 , 20 ); #first 20 lines
ghostdog74