PHP Tutorial - PHP scandir() Function






Definition

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

Syntax

PHP scandir() Function has the following syntax.

scandir(directory,sorting_order,context);

Parameter

ParameterIs RequiredDescription
directoryRequired.Directory to be scanned
sorting_orderOptional.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
contextOptional.Context of the directory handle.

Return

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





Example

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.





Example 2

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