Cheems Bread
Cheems Bread

Reputation: 33

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);

Upvotes: 1

Views: 169

Answers (1)

Barmar
Barmar

Reputation: 780818

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;
}

Upvotes: 2

Related Questions