开发者

How do you make a function read form a txt file and store random lines in a variable? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 year开发者_如何学Cs ago.

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);
  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.


// 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜