Backend Development 4 min read

Reading Files into an Array with PHP's file() Function

This article explains how to use PHP's file() function to read a file's contents into an array, covering its syntax, parameters, optional flags such as FILE_IGNORE_NEW_LINES, and provides clear code examples for practical use.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Reading Files into an Array with PHP's file() Function

In PHP development, reading a file's contents for processing is common, and the file() function is a frequently used tool that reads an entire file into an array, making subsequent manipulation straightforward.

The syntax of file() is:

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

The $filename argument specifies the path to the file (absolute or relative). The optional $flags argument controls how the file is read, and $context can provide a stream context.

Below is a basic example that reads data.txt into an array and outputs each line:

<?php
// Read file contents into an array
$fileContent = file('data.txt');

// Output each line
foreach ($fileContent as $line) {
    echo $line . "<br>";
}
?>

In this example, file() loads every line of data.txt into $fileContent . The foreach loop then iterates over the array, echoing each line with an HTML line break, effectively displaying the whole file.

By default, file() treats each line as a separate array element and automatically strips the trailing newline character when reading.

The function also accepts flags to modify its behavior. For instance, using the FILE_IGNORE_NEW_LINES flag prevents the removal of the newline character at the end of each line:

<?php
// Read file into an array, ignoring newline characters
$fileContent = file('data.txt', FILE_IGNORE_NEW_LINES);

// Output each line
foreach ($fileContent as $line) {
    echo $line . "<br>";
}
?>

This second example demonstrates how the FILE_IGNORE_NEW_LINES flag changes the result by keeping the original line endings, which can be useful when precise formatting is required.

In summary, the file() function is a practical PHP file‑handling utility that quickly loads a file into an array, allowing developers to process file data efficiently and improve development productivity.

backendPHParrayfile handlingphp-functionsfile-read
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

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