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.
$lines = file("names.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
Try it
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.
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
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\nendings. AddFILE_IGNORE_NEW_LINESto strip them. FILE_SKIP_EMPTY_LINESneedsFILE_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()orSplFileObjectfor large files. - Whitespace is preserved, so
trim()each line if indentation or trailing spaces should not count. - Failure returns
falsewith a warning, so compare with=== falsebefore looping. - Not for CSV. Quoted fields can contain newlines; see
fgetcsv(). - Whole string instead:
file_get_contents()followed byexplode("\n", ...)also works but leaves\ron Windows files.