Pull random line from TXT file as string

2019-01-18 23:29发布

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.

标签: php text random
2条回答
【Aperson】
2楼-- · 2019-01-18 23:41

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)];
?>
查看更多
【Aperson】
3楼-- · 2019-01-18 23:42

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

查看更多
登录 后发表回答