Pull random line from TXT file as string

2019-01-18 23:30发布

问题:

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.

回答1:

Make sure your file has read permissions set, should be CHMOD'd to 644 or 744.



回答2:

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)];
?>


标签: php text random