Skip to content
PHP Logo

What potential issues can arise when sorting arrays based on file timestamps in PHP, especially when multiple files have the same timestamp?

When sorting arrays based on file timestamps in PHP, potential issues can arise when multiple files have the same timestamp. This can lead to inconsistent sorting results, as the order of files with the same timestamp may vary between runs. To solve this issue, you can add an additional sorting criterion, such as the file name, to ensure a stable sorting order.

php
// Sample array of file paths
$files = ['file1.txt', 'file2.txt', 'file3.txt'];

// Sort files based on timestamp and then file name
usort($files, function($a, $b) {
    $timestampA = filemtime($a);
    $timestampB = filemtime($b);

    if ($timestampA == $timestampB) {
        return strcmp($a, $b); // Sort by file name if timestamps are equal
    }

    return $timestampA - $timestampB; // Sort by timestamp
});

// Output sorted files
print_r($files);