I have a directory with the files in the following format:

file_0907.pdf
file_1007.pdf
file_1107.pdf
file_1007.pdf
file_1207.pdf
file_0108.pdf
file_0208.pdf
file_0308.pdf

I need to retreive the latest one, not the one saved the latest but the latest in terms of date, i.e. 0308 if March 2008.

They all have the same name, except the four digits standing for month and year.

Having problem figuring it out.

    If this were my problem (being a by my guts programmer) I would read the to an array i.e.:

    0 = file_0907.pdf
    1 = file_1007.pdf
    2 = file_1107.pdf
    3 = file_1007.pdf
    4 = file_1207.pdf
    5 = file_0108.pdf
    6 = file_0208.pdf
    7 = file_0308.pdf

    then a second two dimensional array with the first column as the YEARMONTH of the file name and the second as it's array element in the array as:

    array(0,0) = '0709' array(0,1) = '0'
    array(1,0) = '0710' array(1,1) = '1'
    array(2,0) = '0712' array(2,1) = '2'
    array(3,0) = '0712' array(3,1) = '3'

    etc.

    Then sort the array based on column one and take the first or last element - depending on how you sorted it - and read the send column. That would be the array element of the first array having the oldest/latest file name.

    Not probably the most elegant code, but I never had time to be elegant, just produce. Perhaps someone will be better spoken on this.

      I think this would also work,

      function find_latest($file_array){
            $test = substr($file_array[0], 5, 4);
            foreach($file_array as $tmp){
               if($test < substr($tmp, 5, 4))
                  $test = substr($tmp, 5, 4);
           }
            return $test;
      }
      

        I might do something like:

        <?php
        $files = glob('path/to/files/file_????.pdf');
        function mySort($a, $b)
        {
           $a = (int)('20'.substr($a, -6, 2) . substr($a, -8, 2));
           $b = (int)('20'.substr($b, -6, 2) . substr($b, -8, 2));
           return $b - $a;
        }
        usort($files, 'mySort');
        echo "The latest file is " . $files[0];
        
          Write a Reply...