Re: Reversing the order of a text file
| From: | Zak Greant | Date: | Wed, 31 May 2000 17:58:35 +0000 |
| Subject: | Re: Reversing the order of a text file | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-741@lists.php.net to get a copy of this message | ||
At 12:55 PM 5/31/00 -0400, Brian C. Doyle wrote:
Hello,Hi Brian, Here are some examples with lots of comments. Have fun! /*I have a file info.txt that is a list. I want to read the file in reverse order. How do i go about doing this?
The file function reads in a file and generates an
array from it. Elements in the array will correspond
to lines in the file.
For Example: If you have a file that contains five
lines:
info.txt
--------
Hal (555) 555-5555
Alice (555) 555-5555
Peter (555) 555-5555
Pat (555) 555-5555
Yamuin (555) 555-5555
and you do this:
$array = file ('info.txt')
$array will look like this:
$array[0] = "Hal (555) 555-5555";
$array[1] = "Alice (555) 555-5555";
$array[2] = "Peter (555) 555-5555";
$array[3] = "Pat (555) 555-5555";
$array[4] = "Yamuin (555) 555-5555";
*/
$list = file ('info.txt');
/*
The shortest way is to use the pop function inside
a while loop. Pop grabs removes the last element
from the array and returns it. Note that once you
have looped through the array like this, it will be
empty!
*/
while ($list)
{
print pop ($list) . '<br>';} /*
You can use count to find out the number of elements
in your array, and then use a while loop to loop
backwards through the elements.
Keep in mind that the list array has five elements in
it, however, the last index for the array is 4 - this is
because the first index of the array is 0 - not 1.
*/
$list_length = count ($list);
$current_index = $list_length - 1;
while ($current_index != 0)
{
print $list[$current_index] . '<br>';
# Decrease the value of $current_index by one
--$current_index;
}
/*
You can use reverse on your array and use a while loop
in combination with list and each.
Give the documentation on each a good read before you
start using it a lot. It has a few surprises for
beginners. Each is also the best way to loop through
arrays that contain non-numeric keys.
*/
$list = array_reverse ($list);
while (list ($key) = each ($list))
{
print $list[$key];} Also, there are lots of different ways to do this - these are just a few to get you started. Good Luck! Zak Greant