How to read only 5 last line of the text file in PHP?


To read only 5 last lines of the text file, the code is as follows −

Example

$file = file("filename.txt");
for ($i = max(0, count($file)-6); $i < count($file); $i++) {
   echo $file[$i] . "
"; }

Output

This will produce the following output −

Given that the file has more than 5 lines of text, the last 5 lines of the text file will be displayed.

The file is opened and the number of lines in the file are counted, and beginning from the last line, 5 lines are read.

Updated on: 09-Apr-2020

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements