title besides title

 

Monday, November 26, 2012

PHP : Files - [18.10] Processing a File Backward by Line or Paragraph

18.10.1 Problem

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.

18.10.2 Solution

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

18.10.3 Discussion

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