Backend Development 4 min read

Using PHP's file() Function to Read Files into an Array

This article explains how to use PHP's built‑in file() function to read a text file into an array, demonstrates handling of newline characters, and shows how optional flags like FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES can control line retention and empty‑line skipping.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's file() Function to Read Files into an Array

PHP provides a convenient built‑in function array file ( string $filename [, int $flags = 0 [, resource $context ]] ) that reads an entire file and returns its contents as an array, where each line becomes an element.

To illustrate, create a file named sample.txt with the following content:

<code>Hello, world!
This is a sample file.
It is used for testing file functions in PHP.
</code>

Calling the function without any flags reads the file and retains the line‑ending characters:

<code>$fileContent = file("sample.txt");
print_r($fileContent);
</code>

The resulting array looks like:

<code>Array
(
    [0] => Hello, world!
    [1] => This is a sample file.
    [2] => It is used for testing file functions in PHP.
)
</code>

If you do not want the newline characters, pass the FILE_IGNORE_NEW_LINES flag:

<code>$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES);
print_r($fileContent);
</code>

The output is the same array but without the trailing newlines.

To also skip empty lines, combine FILE_IGNORE_NEW_LINES with FILE_SKIP_EMPTY_LINES :

<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 blank lines, leaving only the non‑empty lines in the array.

In summary, the file() function offers a flexible way to read files into arrays, and its optional flags let you control newline retention and empty‑line filtering to suit various file‑processing needs.

BackendPHParraysfile handlingfile functionflags
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.