Sort Directory Listings

Bookmark and Share

Here is some code to help sort the order of your directory output. This is greate for creating PHP FTP applications.

sort()

General Example 1.

$fruits = array(“lemon”, “orange”, “banana”, “apple”);
sort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo “fruits[".$key."] = “.$val.”\n”;
}
?>

Directory Example 1. A simple scandir() example

$dir = ‘/tmp’;
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);

/* Outputs something like:
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
Array
(
[0] => somedir
[1] => foo.txt
[2] => bar.php
[3] => ..
[4] => .
)
*/

?>

Directory Example 2. PHP 4 alternatives to scandir()

$dir = “/tmp”;
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
print_r($files);

/* Outputs something like:
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
Array
(
[0] => somedir
[1] => foo.txt
[2] => bar.php
[3] => ..
[4] => .
)
*/

?>

Please rate this post by clicking a star:

(1 votes, average: 4.00 out of 5)

One Response to “Sort Directory Listings”

Leave a Reply