Backend Development 4 min read

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

This tutorial explains how PHP's file() function reads a text file into an array, demonstrates the default behavior of preserving line breaks, and shows how to use flags such as FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES to control newline retention and skip empty lines.

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

PHP provides a convenient set of functions for file operations, and the file function is one of the most commonly used to read an entire file and return its contents as an array.

The function prototype is:

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

To illustrate its usage, 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 default call:

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

print_r($fileContent);

produces an array where each line, including the trailing newline character, is an element:

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 to be kept, pass 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 at the end of each element.

You can also combine flags, for example using FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES to remove newlines and skip any empty lines in the file:

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

print_r($fileContent);

This call returns only the non‑empty lines without trailing newlines.

In summary, PHP's file function offers a simple way to read a file into an array, and the optional flags allow fine‑grained control over newline preservation and empty‑line handling, making file processing flexible for various needs.

backendPHPTutorialarraysfile handlingfile function
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.