Src1988
Src1988

Reputation: 193

Usort an array on modified date in php when date is identical

I am trying to sort my array of images by last modified date using the following line.

usort($temp_files, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));

My page is setup to display one image then 4 additional images next to it. But a lot of the images have the same last modified date on the server and I do not have much control over those since the end client uploads them himself. Is there anyway to get around that when the date is identical?

Edit 7/23

So now i have the following, but it still will not sort by date, any ideas?

function cmp_by_filemtime_and_basename($a, $b) {
    $cmp = filemtime($a) - filemtime($b);
    if ($cmp == 0) {
        $cmp = strcmp(basename($a), basename($b));
    }
    return $cmp;
}

usort($temp_files, 'cmp_by_filemtime_and_basename');

Upvotes: 0

Views: 191

Answers (1)

hakre
hakre

Reputation: 198199

You could extend your comparison function to compare the basenames when the filemtime is equal:

function cmp_by_filemtime_and_basename($a, $b) {
    $cmp = filemtime($a) - filemtime($b);
    if (0 == $cmp) {
        $cmp = strcmp(basename($a), basename($b));
    }
    return $cmp;
}

Upvotes: 2

Related Questions