PHP Function Reference

PHP scandir() Function



The PHP scandir() function returns an array of files and directories from the specified directory.

Syntax

scandir(directory, sorting_order, context)

Parameters

directory Required. Specify the directory to be scanned.
sorting_order Optional. Specify the sorting order. Possible values are:
  • 0 or SCANDIR_SORT_ASCENDING: To sort the result in alphabetical ascending order.
  • 1 or SCANDIR_SORT_DESCENDING: To sort the result in alphabetical descending order.
  • 2 or SCANDIR_SORT_NONE: To return the result unsorted.
Default is SCANDIR_SORT_ASCENDING.
context Optional. Specify the context of the directory handle. Context is a set of options that can modify the behavior of a stream.

Return Value

Returns an array of filenames on success, or false on failure. If the specified directory is not a directory, then false is returned, and an error of level E_WARNING is generated.

Example:

The example below shows the usage of scandir() function.

<?php
$dir    = "/temp";

//sorting in ascending order (default)
$files1 = scandir($dir);

//sorting in descending order
$files2 = scandir($dir, 1);

print_r($files1);
echo "\n";
print_r($files2);
?>

The output of the above code will be:

Array
(
    [0] => .
    [1] => ..
    [2] => demo.php
    [3] => example.txt
    [4] => somedir
)

Array
(
    [0] => somedir
    [1] => example.txt
    [2] => demo.php
    [3] => ..
    [4] => .
)

❮ PHP Directory Reference