1

I have a file that is sorted using natsort()...(In ascending order)

But actually i want to sort it in descending order..

I mean the last line of document must be first line and vice versa

Pls let me know is there any function or snippet to achive this..

I'm not that good at php, Appreciate all responses irrespective of quality...Thank You

Megaposie
  • 11
  • 2

4 Answers4

2

use natsort() and than use function array_reverse().

Also refer link
PHP Grab last 15 lines in txt file
it might help you.

Community
  • 1
  • 1
Rikesh
  • 26,156
  • 14
  • 79
  • 87
0

array_reverse will give the contents in descending order

$reverse = array_reverse($array, true);
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
0

Whilst not the most efficient approach for a large text file, you could use file, array_reverse and file_put_contents to achieve this as follows...

<?php
    // Fetch each line from the file into an array
    $fileLines = file('/path/to/text/file.txt');

    // Swap the order of the array
    $invertedLines = array_reverse($fileLines);

    // Write the data back to disk
    file_put_contents('/path/to/write/new/file/to.txt', $invertedLines);
?>

...to achieve what you're after.

John Parker
  • 54,048
  • 11
  • 129
  • 129
0

For longer files:

<?php

function rfopen($path, $mode)
{
    $fp = fopen($path, $mode);
    fseek($fp, -1, SEEK_END);
    if (fgetc($fp) !== PHP_EOL) fseek($fp, 1, SEEK_END);
    return $fp;
}

function rfgets($fp, $strip = false)
{
    $s = '';
    while (true) {
        if (fseek($fp, -2, SEEK_CUR) === -1) { 
            if (!empty($s)) break;
            return false;
        }
        if (($c = fgetc($fp)) === PHP_EOL) break;
        $s = $c . $s;
    }
    if (!$strip) $s .= PHP_EOL;
    return $s;
}

$file = '/path/to/your/file.txt';

$src = rfopen($file, 'rb');
$tgt = fopen("$file.rev", 'w');

while ($line = rfgets($src)) {
    fwrite($tgt, $line);
}

fclose($src);
fclose($tgt);

// rename("$file.rev", $file);

Replace '/path/to/your/file.txt' with the path to your file. Uncomment the last line to overwrite your file.

user1718888
  • 311
  • 2
  • 7