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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
