Master PHP’s file() Function: Read Files into Arrays with Flags
Learn how to use PHP’s built‑in file() function to read a text file into an array, control newline handling with FILE_IGNORE_NEW_LINES, skip empty lines with FILE_SKIP_EMPTY_LINES, and see practical code examples illustrating each option.
In PHP there are many convenient functions for file operations, and the
filefunction is commonly used to read a file’s contents and return them as an array.
Function prototype
<code>array file ( string $filename [, int $flags = 0 [, resource $context ]] )</code>To demonstrate, create a text file
sample.txtwith several lines:
<code>Hello, world!
This is a sample file.
It is used for testing file functions in PHP.</code>Reading the file with the default settings:
<code>$fileContent = file("sample.txt");
print_r($fileContent);</code>The output shows each line as an array element, including the newline characters:
<code>Array
(
[0] => Hello, world!
[1] => This is a sample file.
[2] => It is used for testing file functions in PHP.
)</code>By default the newline at the end of each line is retained. To omit newlines, use the
FILE_IGNORE_NEW_LINESflag:
<code>$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES);
print_r($fileContent);</code>The resulting array no longer contains the newline characters.
You can also combine flags, for example to skip empty lines as well:
<code>$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($fileContent);</code>This call removes both the newline characters and any empty lines, leaving only the non‑empty lines in the array.
In summary, the PHP
filefunction provides a simple way to read a file into an array, with optional flags to control newline retention and empty‑line skipping, giving flexible file‑handling capabilities.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.