Using PHP file() Function to Read Files into an Array
This article explains how the PHP file() function reads a file's contents into an array, details its syntax and parameters, demonstrates basic and flag‑based usage with code examples, and highlights important behaviors such as line handling and newline removal.
In PHP development, reading a file's content for processing is common, and the file() function is a frequently used tool that reads a file into an array for easy manipulation.
The syntax of file() is:
array file ( string $filename [, int $flags = 0 [, resource $context ]] )The $filename parameter specifies the file path (absolute or relative), while $flags and $context are optional parameters for controlling the read operation and providing a stream context.
Below is a basic example that reads the contents of data.txt into an array:
<?php
// Read file content into an array
$fileContent = file('data.txt');
// Output array content
foreach($fileContent as $line) {
echo $line . "<br>";
}
?>This script uses file() to load each line of data.txt into $fileContent , then iterates over the array with foreach to echo each line, demonstrating how the function automatically splits the file by lines.
When reading a file, file() treats each line as a separate array element and, by default, removes the trailing newline character from each line.
The function also accepts flags to modify its behavior; for example, using the FILE_IGNORE_NEW_LINES flag prevents the removal of newline characters.
Example with the FILE_IGNORE_NEW_LINES flag:
<?php
// Read file content into an array and ignore newline characters
$fileContent = file('data.txt', FILE_IGNORE_NEW_LINES);
// Output array content
foreach($fileContent as $line) {
echo $line . "<br>";
}
?>In this case, file() reads data.txt into $fileContent while preserving the original line endings because of the FILE_IGNORE_NEW_LINES flag.
In summary, the file() function is a practical file‑handling utility that quickly loads a file into an array, simplifying further processing and improving development efficiency.
Java学习资料领取
C语言学习资料领取
前端学习资料领取
C++学习资料领取
php学习资料领取
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.