Search code examples
phptext

How do I read the last line to the first file in PHP?


I have it where it prints the file to the body but I need to do that but have the file's data load from the last line to the first.

The code I have right now

$file = fopen('text.txt','r');
while ($line = fgets($file)) {
echo($line);
}
fclose($file);

Solution

  • Use file() to read the file into an array of lines. Then you can reverse the array and loop through it.

    $lines = file('text.txt');
    $lines = array_reverse($lines);
    foreach ($lines as $line) {
        echo $line;
    }