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

Mary-Kate Olsen
Release: 2024-10-27 08:15:03
Original
270 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!