usertest
usertest

Reputation: 27628

PHP: Last file in directory

How do I get the name of the last file (alphabetically) in a directory with php? Thanks.

Upvotes: 3

Views: 5579

Answers (4)

Robert Christie
Robert Christie

Reputation: 20685

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);
?>

Upvotes: 2

prodigitalson
prodigitalson

Reputation: 60413

$files = scandir('path/to/dir');
sort($files, SORT_LOCALE_STRING);
array_pop($files);

Upvotes: 0

suitedupgeek
suitedupgeek

Reputation: 885

Code here looks like it would help - would just need to use end($array) to collect the last value in the generated array.

Upvotes: 0

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340171

Using the Directories extension you can do it simply with

$all_files = scandir("/my/path",1);
$last_files = $all_files[0];

Upvotes: 8

Related Questions