You want to do something with each line of a file, starting at the end. For example, it's easy to add new guestbook entries to the end of a file by opening in append mode, but you want to display the entries with the most recent first, so you need to process the file starting at the end.
If the file fits in memory, use file( ) to read each line in the file into an array and then reverse the array:
$lines = file('guestbook.txt'); $lines = array_reverse($lines);
You can also iterate through an unreversed array of lines starting at the end. Here's how to print out the last 10 lines in a file, last line first:
$lines = file('guestbook.txt'); for ($i = 0, $j = count($lines); $i <= 10; $i++) { print $lines[$j - $i]; }
Documentation on file( ) at http://www.php.net/file and array_reverse( ) at http://www.php.net/array-reverse.
Copyright © 2003 O'Reilly & Associates. All rights reserved.