6.14 Processing a File in Reverse


You want to process each line of a text file in reverse.

Technique

Read all the lines into an array and then reverse the array to loop through it (the code illuminates my meaning):

 <?php $f_contents = array_reverse (file ($fn)); foreach ($f_contents as $backwards_line) {     print $backwards_line; } ?> 

Comments

There are certain limitations on accessing files, and not being inherently able to loop backward through files is one of those limitations. Therefore, the simplest way is simply to load the file into an array of lines, reverse the array, and then process the array. You can also loop backward through the file lines to avoid the expense of array_reverse() :

 <?php $f_contents = file ($fn); for ($n = count ($f_contents) - 1; $n >= 0; $n--)     print $f_contents[$n]; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net