Search code examples
phpsortingfilenamesnatural-sort

How to read the last two files in a directory by comparing filenames naturally?


I just figured out how to read some files but I really don't like it.

I have some files named 1.txt, 2.txt, 3.txt and so on. I need to read and print just the last 2 files. I found a way to do it but I would like to see some other ways to do it.

My way:

$i = 1;
$x = 1;

while (file_exists('news/' . $i . '.txt')) {
    $i++;
}

$i--;

while ((file_exists('news/' . $i . '.txt')) && ($x <= 2)) {
    $data = file_get_contents('news/' . $i . '.txt'); 
    echo $data;
    $i--;
    $x++;
}

Solution

  • There might be a problem with the scandir() approach: The file names are sorted lexicographically, i.e. 1.txt, 10.txt, 11.txt, 2.txt, 20.txt, 3.txt,...
    Therefore if you really want to change your code I'd suggest scandir()/glob() and natsort():

    This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations.
    $files = glob('news/*.txt');
    natsort($files);
    $files = array_slice($files, -2);