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