Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to read only 5 last line of the text file in PHP?
In PHP, you can read only the last 5 lines of a text file using the file() function combined with array slicing. The file() function reads the entire file into an array where each line becomes an array element.
Using file() Function
This method loads the entire file into memory and extracts the last 5 lines ?
<?php
$file = file("filename.txt");
$totalLines = count($file);
$startIndex = max(0, $totalLines - 5);
for ($i = $startIndex; $i < $totalLines; $i++) {
echo $file[$i];
}
?>
Using array_slice() Method
A more concise approach using array_slice() to get the last 5 elements ?
<?php
$file = file("filename.txt", FILE_IGNORE_NEW_LINES);
$lastFiveLines = array_slice($file, -5);
foreach ($lastFiveLines as $line) {
echo $line . "<br>";
}
?>
Memory-Efficient Method for Large Files
For very large files, reading line by line from the end is more memory-efficient ?
<?php
$file = fopen("filename.txt", "r");
$lines = [];
$lineCount = 0;
while (($line = fgets($file)) !== false) {
$lines[] = $line;
$lineCount++;
if ($lineCount > 5) {
array_shift($lines);
}
}
fclose($file);
foreach ($lines as $line) {
echo $line;
}
?>
Output
For a file containing multiple lines, the output will display the last 5 lines ?
Line 6 of the file Line 7 of the file Line 8 of the file Line 9 of the file Line 10 of the file
Conclusion
Use array_slice() for small files and the memory-efficient method for large files. Always check if the file exists using file_exists() before reading to avoid errors.
Advertisements
