The scandir() function returns an array of files and directories of the specified directory.
PHP scandir() Function has the following syntax.
scandir(directory,sorting_order,context);
Parameter | Is Required | Description |
---|---|---|
directory | Required. | Directory to be scanned |
sorting_order | Optional. | Sorting order. Default sort order is alphabetical in ascending order (0). Set to SCANDIR_SORT_DESCENDING or 1 to sort in alphabetical descending order, or SCANDIR_SORT_NONE to return the result unsorted |
context | Optional. | Context of the directory handle. |
Returns an array of files and directories on success. FALSE on failure.
Throws an error of level E_WARNING if directory is not a directory
The scandir() function returns an array of all files and directories. If the second parameter is set to 1, scandir() function will sort the array returned reverse alphabetically.
If it is not set, the array is returned sorted alphabetically.
<?PHP
$files = scandir(".", 1);
var_dump($files);
// Sort in ascending order - this is default
$a = scandir(".");
print_r($a);
?>
The code above generates the following result.
The following code shows how to list files and directories inside the images directory.
//from w w w .j ava 2s.co m
<?php
$dir = "/img/";
// Sort in ascending order - this is default
$a = scandir($dir);
// Sort in descending order
$b = scandir($dir,1);
print_r($a);
print_r($b);
?>