Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

file

Reads a file into an array of lines.

Syntax

file(string $filename, int $flags = 0): array|false

Parameters

ParameterTypeDescription
$filenamestringThe path to the file.
$flagsintOptional. `FILE_IGNORE_NEW_LINES` strips line breaks, `FILE_SKIP_EMPTY_LINES` skips empty lines.

Return value

array|falseAn array of the file's lines, or `false` on failure.

Examples

The lines of a file as a list:

<?php
 
$file = sys_get_temp_dir() . '/ref-lines.txt';
file_put_contents($file, "apple\npear\nplum\n");
 
$lines = file($file, FILE_IGNORE_NEW_LINES);
 
echo count($lines), ': ', implode(', ', $lines);

Output:

3: apple, pear, plum

Notes

Without the FILE_IGNORE_NEW_LINES flag every line keeps its trailing line break.

See also

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.