How can PHP developers optimize the code provided to efficiently read the last line of the file in question?
The issue with the current code provided is that it reads the entire file into an array and then returns the last element, which can be inefficient for large files. To optimize this, we can use a more efficient approach by reading the file line by line until we reach the end, thus avoiding unnecessary memory usage.
$file = 'example.txt';
$lastLine = '';
$handle = fopen($file, 'r');
if ($handle) {
while (($line = fgets($handle)) !== false) {
$lastLine = $line;
}
fclose($handle);
}
echo $lastLine;
Keywords
Related Questions
- What common errors should be avoided when converting a date to Unix format in PHP?
- What are the advantages of using a database instead of arrays for storing image descriptions and related information in PHP?
- Are there any best practices for efficiently processing form data in PHP without using numerous isset($_POST['fieldname']) checks?