0

I am trying to show images on my website with php usort, so the new images should be at the top and the oldest at the bottom. I tried to use usort, but it is not working and the images are still displayed the opposite way, the old ones are at the top and the new ones are at the bottom. Is something wrong with my code, or why is it happening? (I read all of the topics here at stackoverflow that have something in common, but I did not figured out what is wrong.)

I use this code:

$folder_path = 'posters/';

$num_files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);
usort( $num_files, function( $a, $b ) { return filemtime($a) < filemtime($b); } );

$folder = opendir($folder_path);
user7176800
  • 29
  • 1
  • 7

2 Answers2

0

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

You're returning a boolean (true/false). Try swapping the < with a -. And if what you get is the reverse of what you should have, swap $a with $b and it should order it the right way.

Svish
  • 152,914
  • 173
  • 462
  • 620
  • I used the `-` before and I also tried to swap the `$a` with `$b` but I did not found any of it working, so you suggesting that it should look like this?: `usort( $num_files, function( $a, $b ) { return filemtime($a) - filemtime($b); } );` or like this: `usort( $num_files, function( $b, $a ) { return filemtime($a) - filemtime($b); } );` ? – user7176800 Apr 05 '17 at 20:48
  • Whichever sorts in the right direction. "Not found any of it working", in what way? What isn't working? How is it not working? What are you expecting, that doesn't happen? – Svish Apr 06 '17 at 13:44
0

You can use filemtime() function which Gets file modification time. In this case you will get all image list ascending order so you want to show list as last modify time , in this case need to reverse all image using usort() function with custom function which compare modify time then list it .

<?php
function latestImageProcess($compare1, $compare2)
{
    $first_compare = filemtime($compare1);
    $second_compare = filemtime($compare2);

    if ($first_compare == $second_compare) {
        return 0;
    }
    else if ($first_compare < $second_compare) {
        return -1;
    }
    else {
        return 1;
    }
}

$images_list = glob("posters/*.*");
usort($images_list, "latestImageProcess");

for ($i = count($images_list) - 1; $i >= 0; $i--) {
    $image_name = $images_list[$i];
    echo '<img src="' . $image_name . '" height ="400" title="'.$image_name.'"/><br />';
}
?>

hope this will help you and for more information about filemtime

http://php.net/manual/en/function.filemtime.php

Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43