PHP file() Function

Definition and Usage

The file() function reads the entire file into an array.

With file_get_contents() Similarly, the difference is that the file() function returns the file as an array. Each element of the array is a line from the file, including the newline character.

If the operation fails, it returns false.

Syntax

file(path,include_path,context)
Parameters Description
path Required. Specifies the file to be read.
include_path Optional. If you also want to search for files in the include_path, you can set this parameter to "1".
context

Optional. Specifies the environment for the file handle.

context is a set of options that can modify the behavior of the stream. If null is used, it is ignored.

Description

on context support was added in PHP 5.0.0.

Each line in the returned array includes a line ending, so if you do not need line endings, you also need to use the rtrim() function.

Tips and Comments

Note:Starting from PHP 4.3.0, it can be used file_get_contents() to read the file into a string and return it.

Note:Starting from PHP 4.3.0, the file() function can be used safely for binary files.

Note:If PHP cannot recognize the line endings of Macintosh files when reading files, you can activate the auto_detect_line_endings runtime configuration option.

Example

<?php
print_r(file("test.txt"));
?>

Output:

Array
(
[0] => Hello World. Testing testing!
[1] => Another day, another line.
[2] => If the array picks up this line,
[3] => then is it a pickup line?
)