Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

php - Pull random line from TXT file as string

I'm currently using the code below to try and read a random line from random.txt and pass it as $data, however it comes back empty. Each string has its own line, am I missing something here? Shouldn't this work? If not how can I get a random line from my text file and use it as my $data string?

$f_contents = file("random.txt");
$line = $f_contents[array_rand($f_contents)];
$data = $line;

Solved - Bad CHMOD Thought I had double checked it, sorry to post a question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code looks correct, but you can try it this way too:

<?php
    $f_contents = file("random.txt"); 
    $line = $f_contents[rand(0, count($f_contents) - 1)];
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...