tags:

views:

69

answers:

5

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
`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
One would expect it to be the same sort sort() does, using the string option.
Vinko Vrsalovic
@Ignacio: According to http://uk.php.net/manual/en/function.scandir.php, the 'default sort order is alphabetical in ascending order'
Robert Christie
@cb160: What does "alphabetical" mean when you mix German, Japanese, and Korean?
Ignacio Vazquez-Abrams
@Ignacio: Good point.
Robert Christie
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
I presume you only meant to have one `=` in the line `$last_file = = $files[0];` though?
PeterJCLaw
@PeterJClaw: Thanks - have corrected the answer.
Robert Christie
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
hm, other answers are much neater.
foxed
A: 
$files = scandir('path/to/dir');
sort($files, SORT_LOCALE_STRING);
array_pop($files);
prodigitalson
A: 

scandir also lists dirs in dir, so be careful.

nit
This should be a comment.
zombat