PHP Directory scandir() Function (With Examples)

In this tutorial, we will learn about the PHP scandir() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP scandir() function

The full form of scandir is "Scan Directory", the function scandir() is used to get the list of the files and directories available in the specified directory.

Syntax

The syntax of the scandir() function:

scandir(directory, sorting_order, context);

Parameters

The parameters of the scandir() function:

  • directory – It specifies the directory name (or path) from there we have to get the list of the files and directories
  • sorting – It is an optional parameter; its default value is o (alphabetically sorting order). 1 can be used to descending order.
  • context – It is an optional parameter; it is used to specify the context (a set of options that can modify the behavior of the stream) to the directory handle.

Return Value

It returns an array of the files and directories, returns "False" on function execution failure.

PHP scandir() Function Example

PHP code to get and print the list of files and directories of a given directory.

<?php
//directory name
$path = "/home";

//assigning the return array in $arr1
//defualt in ascending order
$arr1 = scandir($path);

//assigning the return array in $arr2
//Using 1 for descending order
$arr2 = scandir($path,1);

//printing the results
print_r($arr1);
print_r($arr2);
?>

Output

The output of the above example is:

Array
(
    [0] => .
    [1] => ..
    [2] => folder1
    [3] => folder2
    [4] => folder3
    [5] => main.php
)
Array
(
    [0] => main.php
    [1] => folder3
    [2] => folder2
    [3] => folder1
    [4] => ..
    [5] => .
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.