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.
One way to do it:
$contents = file('myfile.txt');
shuffle($contents);
array_splice($contents, 5);
var_dump($contents);
- Reads the whole file into an array
- Shuffles the array
- 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.
// 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 );
$file = file( $path );
shuffle( $file );
$random_lines = array_slice( $lines , 0 , 20 ); #first 20 lines
精彩评论