Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP file() function

Reference for PHP file(): read a file into an array with one element per line, the FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES flags, and failure behavior.

file() reads a whole file and returns it as an array, one element per line. By default every element keeps its trailing newline, which is rarely what you want, so most calls pass FILE_IGNORE_NEW_LINES. It is convenient for small files such as lists, configuration and logs.

Like file_get_contents(), it loads everything into memory. For big files, loop with fgets() instead.

PHP
$lines = file("names.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Try it

PHP Lines with and without newlines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Numbering lines and handling a missing file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
file(string $filename, int $flags = 0, ?resource $context = null): array|false
Name Description
$filename Path or stream URL to read.
$flags Any combination of FILE_USE_INCLUDE_PATH, FILE_IGNORE_NEW_LINES and FILE_SKIP_EMPTY_LINES.
$context Optional stream context.

Return value: an array of lines (keys 0, 1, 2, ...), or false on failure. An empty file gives an empty array.

Usage notes

  • Newlines are kept by default, including \r\n endings. Add FILE_IGNORE_NEW_LINES to strip them.
  • FILE_SKIP_EMPTY_LINES needs FILE_IGNORE_NEW_LINES. Without it, a blank line is still "\n" and is not empty.
  • A last line without a trailing newline is still returned as an element.
  • Memory use is proportional to the file size. Use fgets() or SplFileObject for large files.
  • Whitespace is preserved, so trim() each line if indentation or trailing spaces should not count.
  • Failure returns false with a warning, so compare with === false before looping.
  • Not for CSV. Quoted fields can contain newlines; see fgetcsv().
  • Whole string instead: file_get_contents() followed by explode("\n", ...) also works but leaves \r on Windows files.