0

I have a folder called images I want to access the last file From Folder and the naming of the images like AB00001.png and for the second image ImageName-AB00002 so on. Whenever it reaches ImageName-AB000010, in this case, getting the last image as ImageName-AB00009, but not ImageName-AB000010.

// scanning last file   
$files = scandir('../images/', SCANDIR_SORT_DESCENDING);
//for name of last file
echo $newest_file = $files[0];
// for substring after hyphen
$lclStrAfterHyphen = substr($newest_file, strpos($newest_file, "-") + 1);
// checking string length
echo strlen($lclStrAfterHyphen);
Samson
  • 352
  • 1
  • 11
  • why you deleted the post. – Samson Jun 27 '19 at 05:56
  • Just hit the wrong link ;) – CodyKL Jun 27 '19 at 05:58
  • ok, now if the image name length is for example 5 then getting the last image but if it is 6 then getting length 5 image itself. – Samson Jun 27 '19 at 06:02
  • What do you mean with image name length? Is the prefix "ImageName-" always the same or different? – CodyKL Jun 27 '19 at 06:05
  • The image name will be different. – Samson Jun 27 '19 at 06:08
  • I am giving hyphen for differentiating name and unique code. – Samson Jun 27 '19 at 06:11
  • check this [link](https://stackoverflow.com/questions/11923235/scandir-to-sort-by-date-modified) here & [this](https://stackoverflow.com/questions/2667065/sort-files-by-date-in-php) – danish-khan-I Jun 27 '19 at 06:20
  • The flag `SCANDIR_SORT_DESCENDING` sorts the file name ascending, Make sure the length of the filename is correct. '01' is different than '010' or '10'. Use something like `sprintf('%08d.jpg', $number);` to get it consistant. This will make sure `$number` will always be 8 digits with automatic adapted leading zeros. If you need to have the last modified/created file, use a FileSystemIterator and sort by the SplFileInfo properties. – Markus Zeller Jun 27 '19 at 07:21

1 Answers1

0

Works as expected:

$files = scandir(__DIR__.'/files', SCANDIR_SORT_DESCENDING);
print_r($files);
/*
 * OUTPUT:
 * Array
 * (
 *    [0] => testfile010.txt
 *    [1] => testfile009.txt
 *    [2] => testfile008.txt
 *    [3] => testfile007.txt
 *    [4] => testfile006.txt
 *    [5] => testfile005.txt
 *    [6] => testfile004.txt
 *    [7] => testfile003.txt
 *    [8] => testfile002.txt
 *    [9] => testfile001.txt
 *    [10] => ..
 *    [11] => .
 */
CodyKL
  • 1,024
  • 6
  • 14
  • if the image is like testfile010.txt working if contains extra zero like testfile0010.txt then it is not working. – Samson Jun 27 '19 at 06:04