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.

php Courses
php Courses
php Courses
Master PHP’s file() Function: Read Files into Arrays with Flags

In PHP there are many convenient functions for file operations, and the file function is commonly used to read a file’s contents and return them as an array.

Function prototype

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

To demonstrate, create a text file sample.txt with several lines:

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

Reading the file with the default settings:

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

The output shows each line as an array element, including the newline characters:

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

By default the newline at the end of each line is retained. To omit newlines, use the FILE_IGNORE_NEW_LINES flag:

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

The resulting array no longer contains the newline characters.

You can also combine flags, for example to skip empty lines as well:

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

This call removes both the newline characters and any empty lines, leaving only the non‑empty lines in the array.

In summary, the PHP file function 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.

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.

BackendArrayfile-handlingFile
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.