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;