4
$files = scandir(__DIR__, SCANDIR_SORT_DESCENDING);

First I tried to check if there is sorting type for the date, but sadly I couldn't find one so I decided to use filemtime

$latest = date("d Y H:i:s.");
printf($latest);
foreach($files as $value) {
    if ($value != "..") {
        if($value != ".") {
            $latestnew = date("d Y", filemtime($value));

            if($latestnew > $latest) {
                $latest = $value;
            }
        }
    }
}
printf($latest);

You can see that I've a array which many files in it. The latest file name should be in in the $latest variable. I know that the ">" check does not work but I was not able to find another solution. Thanks.

Florian Zaskoku
  • 477
  • 3
  • 13

2 Answers2

2

According to the PHP Manual:

int filemtime ( string $filename )

Returns the time the file was last modified, or FALSE on failure. The time is returned as a Unix timestamp, which is suitable for the date() function.

Comparing integers is far more easy and comfortable than comparing formats of date.

$latestFilename = '';
$latestTime = 0;    
foreach($files as $filename) {
        if ($filename != "..") {
            if($filename != ".") {
                $currentFileTime = filemtime($filename);

                if($currentFileTime > $latestTime) {
                    $latestFilename = $filename;
                    $lastestTime = $currentFileTime;
                }
            }
        }
    }

Another option would be to create a DateTime object and to use the defined compare method.

Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39
1

Since you're starting with the current time right now, no file should really be newer than right now - and you're assigning the name of the file for further comparison, instead of the actual timestamp you want to check. Instead of converting everything to a date, keep the actual timestamp. That's way more suitable for comparison, and keep the file name in a separate variable.

$latest = 0;
$latest_name = null;

foreach($files as $value) {
    if (($value != "..") && ($value != ".")) {
        $latestnew = filemtime($value);

        if($latestnew > $latest) {
            $latest = $latestnew;
            $latest_name = $value;
        }
    }
}

print(date("d Y H:i:s", $latest) . ' - ' . $latest_name);

This will print the formatted timestamp of the latest file, and its name. You might also want to prefix $value with the path to the file if it's not in the current directory when calling filemtime. I.e. filemtime($path . '/' . $value);

MatsLindh
  • 49,529
  • 4
  • 53
  • 84