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.
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)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With