Home  >  Article  >  Backend Development  >  How to Efficiently Read Each Line of a Text File into an Array Element?

How to Efficiently Read Each Line of a Text File into an Array Element?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 08:15:03271browse

How to Efficiently Read Each Line of a Text File into an Array Element?

Reading Each Line of a Text File into an Array Element

Problem: You want to read each line of a text file into an array, with each line as a separate element.

Example Code:

<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>

Proposed Solution:

The provided code has a flaw in that it uses explode('n') to split the line, which may not be appropriate for all scenarios. A better approach is to utilize file() with FILE_IGNORE_NEW_LINES to read the file line-by-line and store each line as an array element.

Code:

<code class="php">$lines = file($filename, FILE_IGNORE_NEW_LINES);</code>

The above is the detailed content of How to Efficiently Read Each Line of a Text File into an Array Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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