getFileLines.php
Table of Contents
Functions
- getFileLines() : array<string|int, mixed>|null
- Retrieves all lines from a file as an array, optionally transforming each line with a callback.
Functions
getFileLines()
Retrieves all lines from a file as an array, optionally transforming each line with a callback.
getFileLines(string|null $file[, callable|null $map = null ][, int|null $maxBytes = null ]) : array<string|int, mixed>|null
This function uses a generator internally (getFileLinesGenerator) to read the file line by line,
which allows efficient processing of large files. Each line can optionally be mapped using the
provided callable.
Example usage:
use function oihana\files\getFileLines;
$lines = getFileLines('/path/to/file.log');
// Using a mapping function to parse CSV lines
$csvLines = getFileLines('/path/to/data.csv', fn($line) => str_getcsv($line));
// Refusing files larger than 10 MiB (defensive cap on untrusted sources).
$lines = getFileLines('/path/to/upload.log', null, 10 * 1024 * 1024);
Parameters
- $file : string|null
-
The full path to the file to read.
- $map : callable|null = null
-
Optional mapping function applied to each line. Signature: fn(string $line): mixed
- $maxBytes : int|null = null
-
Optional cap on the file size (in bytes). When set,
getFileLines()rejects any file whose size exceeds this value before opening it, throwing RuntimeException. Defaultnull(no limit — historical behaviour). Useful as a defensive guard against OOM when the caller does not fully trust the size of the input.
Tags
Return values
array<string|int, mixed>|null —Returns an array of lines (or mapped values). Returns an empty array if the file is empty.