Home > Article > Backend Development > How to Properly Read and Store Lines from a Text File in an Array in PHP?
Accessing Text Lines in an Array
When working with text files in programming, it's often necessary to store each line of text in an organized data structure for further processing.
In the provided PHP code snippet:
<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>
The issue with this code is that it incorrectly attempts to split each line into array elements using 'n', which represents the line break character. This will only result in capturing the last line in the file into an array.
To correctly read each line of the text file into an array and have each line in a new element, a more appropriate method is to use the file() function as follows:
<code class="php">$lines = file($filename, FILE_IGNORE_NEW_LINES);</code>
By specifying the FILE_IGNORE_NEW_LINES flag, the file() function reads the entire file into an array, with each element representing a single line of the text file while excluding any line breaks.
The above is the detailed content of How to Properly Read and Store Lines from a Text File in an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!