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!