Using PHP's file() Function to Read Files into an Array
This tutorial explains how PHP's file() function reads a text file, returns each line as an array element, and how optional flags like FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES can control newline retention and empty‑line handling.
In PHP there are many convenient functions for file operations, and the file() function is one of the most commonly used because it reads a file and returns its contents as an array.
The function prototype is:
array file ( string $filename [, int $flags = 0 [, resource $context ]] )To demonstrate, create a text file named sample.txt with the following content:
Hello, world!
This is a sample file.
It is used for testing file functions in PHP.Reading the file with the basic call:
$fileContent = file("sample.txt");
print_r($fileContent);produces an array where each line, including the line‑break character, is an element:
Array
(
[0] => Hello, world!
[1] => This is a sample file.
[2] => It is used for testing file functions in PHP.
)By default the newline character is kept. To omit it, use the FILE_IGNORE_NEW_LINES flag:
$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES);
print_r($fileContent);The output now shows the lines without trailing newlines.
Additional flags can modify the behavior further. For example, FILE_SKIP_EMPTY_LINES skips empty lines. Combining flags works as shown:
$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($fileContent);The resulting array contains only the non‑empty lines, with newlines removed.
In summary, PHP's file() function provides a simple yet flexible way to read a file into an array, and its optional flags allow precise control over newline retention and empty‑line handling.
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.