Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random lines from text file

Tags:

arrays

file

php

I want to call random words from the random.txt as the user refreshes the page but I get $word_array[0] only and not any other $word_array[1..3].

random.txt

hello
how
are
you

PHP code:

myfile = fopen("random.txt", "r") or die("Unable to open file!");
$word_array = array(fgets($myfile));

$word = rand(0,4);
$lines[] = fgets($myfile);
echo $word_array[$word];

fclose ($myfile); 

What is the error?

update: If loops can be avoided, and correct this code only.

like image 781
X10nD Avatar asked Nov 15 '25 12:11

X10nD


1 Answers

The problem in your code is, that you put just the first line of your file into an array here:

$word_array = array(fgets($myfile));

Means what you have here is:

Array (
    [0] => First line
)

So if you have error reporting turned on you would get a notice:

Notice: Undefined offset

75% of the time.

But to do what you want you can just use file() to get your file into an array combined with array_rand(), e.g.

$lines = file("random.txt");
echo $lines[array_rand($lines)];
like image 68
Rizier123 Avatar answered Nov 17 '25 07:11

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!