Reading Text File Lines into Array Elements
Question:
In this code snippet for reading a text file line by line into an array:
<code class="php">$file = fopen("members.txt", "r"); while (!feof($file)) { $line_of_text = fgets($file); $members = explode('\n', $line_of_text); } fclose($file);</code>
Why does the $members array contain only the last line of the text file, rather than an element for each line?
Answer:
The provided code correctly reads lines from the text file but encounters an issue in creating the array of lines. Using explode('n', $line_of_text) within the loop overwrites the $members array in each iteration, ultimately storing only the last line.
To resolve this issue, use file function instead:
<code class="php">$lines = file($filename, FILE_IGNORE_NEW_LINES);</code>
This function directly creates an array where each element represents a line from the text file. Using FILE_IGNORE_NEW_LINES skips the newline character from each line, ensuring the array contains only the line content.
The above is the detailed content of Why does my code only store the last line of the text file in the array, instead of all lines?. For more information, please follow other related articles on the PHP Chinese website!