How do I get the name of the last file (alphabetically) in a directory with php? Thanks.
+1
A:
Using the Directories extension you can do it simply with
$all_files = scandir("/my/path",1);
$last_files = $all_files[0];
Vinko Vrsalovic
2010-01-19 21:49:36
`scandir()` does not specify *which* sorting it uses, so your results may be inaccurate if you have files with non-ASCII characters.
Ignacio Vazquez-Abrams
2010-01-19 21:51:38
One would expect it to be the same sort sort() does, using the string option.
Vinko Vrsalovic
2010-01-19 21:54:16
@Ignacio: According to http://uk.php.net/manual/en/function.scandir.php, the 'default sort order is alphabetical in ascending order'
Robert Christie
2010-01-19 21:54:18
@cb160: What does "alphabetical" mean when you mix German, Japanese, and Korean?
Ignacio Vazquez-Abrams
2010-01-19 21:56:28
@Ignacio: Good point.
Robert Christie
2010-01-19 22:04:47
A:
The scandir command returns an array with the list of files in a directory. The second parameter specifies the sort order (defaults to ascending, 1 for descending).
<?php
$dir = '/tmp';
$files = scandir($dir, 1);
$last_file = $files[0];
print($last_file);
?>
Robert Christie
2010-01-19 21:51:59
I presume you only meant to have one `=` in the line `$last_file = = $files[0];` though?
PeterJCLaw
2010-01-19 21:56:45
A:
Code here looks like it would help - would just need to use end($array) to collect the last value in the generated array.
foxed
2010-01-19 21:52:19
A:
$files = scandir('path/to/dir');
sort($files, SORT_LOCALE_STRING);
array_pop($files);
prodigitalson
2010-01-19 21:56:21