Backend Development 4 min read

Using PHP file() Function to Read Files into an Array

This article explains how to use PHP's file() function to read a file's contents into an array, describes its syntax and parameters, demonstrates basic and flag‑enhanced usage with code examples, and highlights important behaviors such as automatic newline removal.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP file() Function to Read Files into an Array

In PHP development, it is often necessary to read the contents of a file for processing. PHP provides a series of file handling functions, among which the very common file() function reads a file’s contents into an array, making it easy to manipulate.

The syntax of file() is:

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

Parameters:

filename : the name of the file to read, which can be an absolute or relative path.

flags : optional flags that specify how the file should be read.

context : optional resource that defines the file’s context.

Below is a concrete example demonstrating how to use file() to read a file’s contents into an array:

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

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

In this example, file() reads the contents of data.txt into the array $fileContent . The foreach loop then iterates over the array, outputting each line to the browser, allowing the entire file to be read at once.

When reading a file, file() automatically treats each line as an array element and removes the trailing newline character from each line.

Beyond simply reading file contents, file() can accept additional parameters to modify its behavior. For example, the second parameter flags can be set to FILE_IGNORE_NEW_LINES to ignore the newline at the end of each line.

Example with the FILE_IGNORE_NEW_LINES flag:

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

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

This example shows that file() reads data.txt into $fileContent while the FILE_IGNORE_NEW_LINES flag prevents newline characters from being included.

In summary, the file() function is a highly useful file handling function that conveniently reads file contents into an array, facilitating easier processing and improving development efficiency.

backend developmentPHParrayfile handlingfile()
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.