Sort Directory Listings

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] => .
)
*/

?>

One thought on “Sort Directory Listings

Leave a Reply

Your email address will not be published. Required fields are marked *