Home > Backend Development > PHP Tutorial > Why does my code only store the last line of the text file in the array, instead of all lines?

Why does my code only store the last line of the text file in the array, instead of all lines?

DDD
Release: 2024-10-29 03:09:02
Original
772 people have browsed it

Why does my code only store the last line of the text file in the array, instead of all lines?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template