4

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.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
X10nD
  • 21,638
  • 45
  • 111
  • 152

4 Answers4

6

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)];
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0

fgets are read only one line by line. so you need something like:

$lines[] = fgets($myfile);
$lines[] = fgets($myfile);
$lines[] = fgets($myfile);
$lines[] = fgets($myfile);
echo $lines[$word];

4 times for 4 lines

0

Short: fgets just read one line You need to create a while-statement to read all lines.

So:

$array = explode("\n", file_get_contents('random.txt'));

http://php.net/manual/en/function.fgets.php

Read each line of txt file to new array element

Community
  • 1
  • 1
DogeAmazed
  • 858
  • 11
  • 28
0

Interesing question=) You can try my solution:

$myfile = fopen("random.txt", "r") or die("Unable to open file!");
$words = fgets($myfile);//gets only first line of a file
$num = str_word_count($words) - 1 ;//count number of words, but array index
//starts from 0, so we need -1
$word_array = explode(' ', $words);//gets all words as array

$word = rand(0,$num);//getting random word number
echo $word_array[$word];

fclose ($myfile); 

if you need all lines - you have to iterate over all lines with, for example, while loop

while($row = fgets($myfile)){
    //same code
}
Dmitrii Cheremisin
  • 1,498
  • 10
  • 11