Asked
Viewed
4.5k times

I can read it line by line forward but now I am wondering how to read it line by line backwards. Probably the easiest way is to either reverse the array or change the foreach statement but Im not sure how to do either.

add a comment
0

3 Answers

  • Votes
  • Oldest
  • Latest
JO
144 4
Answered

Read the lines into an array backwards with 'fgets()' & 'array_unshift()'.

Basic example,

<?php
	$file_array = array();

	$handle = fopen('test.txt', 'r');
	while (!feof($handle)) {
		$line = fgets($handle, 4096);
		array_unshift($file_array, $line);
	}
	fclose($handle);

	foreach($file_array as $line){
		echo $line . '<hr/>';
	}
?>
add a comment
0
Answered

This is a little more simple:

<?php
$data = file ( "text.txt" );              // open the file and put each line in an array element

$reverse_data = array_reverse ( $data );  // use array_reverse to reverse it

   foreach ( $reverse_data as $line )     // print it out
   {
      echo $line . "<br />";
   }
?>
add a comment
0
Answered

Wow. Had no idea it was so simple. Thank you.

add a comment
0