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

This article explains how PHP’s file() function reads a text file into an array, demonstrates the default behavior of preserving line endings, and shows how to use flags such as FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES for more flexible file handling.

php Courses
php Courses
php Courses
Using PHP’s file() Function to Read Files into an Array

In PHP, the file function reads a file and returns its contents as an array, with each line as an element.

The function prototype is

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

.

First, create a sample file sample.txt containing:

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

Reading the file with $fileContent = file("sample.txt"); print_r($fileContent); produces an array where each line includes the newline character.

To omit newlines, use the FILE_IGNORE_NEW_LINES flag:

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

.

Additional flags such as FILE_SKIP_EMPTY_LINES can be combined (e.g., FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) to skip empty lines while reading.

These options allow flexible handling of file input in PHP backend development.

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.

BackendPHPfile-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

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.