Master PHP’s file() Function: Read Files into Arrays Effortlessly
This guide explains how PHP’s file() function reads an entire file into an array, details its syntax and parameters, demonstrates basic and flag‑enhanced usage with code examples, and highlights important considerations such as automatic newline removal for efficient backend development.
In PHP development, you often need to read a file’s contents for processing. PHP provides the file() function, which reads a file into an array, making it easy to manipulate the data.
The syntax is:
array file ( string $filename [, int $flags = 0 [, resource $context ]] ) $filenameis the path to the file (absolute or relative). $flags is optional and controls how the file is read. $context is an optional stream context.
Basic example:
<?php
// Read file contents into an array
$fileContent = file('data.txt');
// Output each line
foreach ($fileContent as $line) {
echo $line . "<br>";
}
?>This code reads data.txt into $fileContent, then loops through the array to output each line.
Note that file() automatically splits the file by lines and removes the trailing newline character from each element.
You can modify the behavior with flags. For example, using FILE_IGNORE_NEW_LINES prevents the removal of newline characters:
<?php
// Read file into array, ignoring new lines
$fileContent = file('data.txt', FILE_IGNORE_NEW_LINES);
// Output each line
foreach ($fileContent as $line) {
echo $line . "<br>";
}
?>In this example, the flag ensures that each line is kept exactly as it appears in the file.
Overall, the file() function is a practical tool for quickly loading file data into an array, simplifying further processing and improving development efficiency.
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.
