Home » PHP

PHP scandir() function with example

PHP scandir() function: Here, we are going to learn about the PHP scandir() function with its syntax, parameters, returns type, and example.
Submitted by IncludeHelp, on August 11, 2019

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:

    scandir(directory, sorting_order, context);

Parameter(s):

  • 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.

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

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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.