file
Reads a file into an array of lines.
Syntax
file(string $filename, int $flags = 0): array|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $filename | string | The path to the file. |
| $flags | int | Optional. `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, plumNotes
Without the FILE_IGNORE_NEW_LINES flag every line keeps its trailing line break.
See also
- file_get_contents — Reads a whole file into a string.
- explode — Splits a string into an array by a separator.
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.