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:

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

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

$fileContent = file("sample.txt");
print_r($fileContent);

The resulting array looks like:

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

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

$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES);
print_r($fileContent);

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:

$fileContent = file("sample.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($fileContent);

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPArraysfile 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

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.