The scandir() function in PHP is an inbuilt function which is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.
The directory, stream behavior and sorting_order of the files and directories are passed as a parameter to the scandir() function and it returns an array of filenames on success, or False on failure.
scandir(directory, sorting_order, context);
The scandir() function in PHP accepts three parameters.
- directory : It is a mandatory parameter which specifies the path.
- sorting_order: It is an optional parameter which specifies the sorting order. Alphabetically ascending order (0) is the default sort order. It can be set to SCANDIR_SORT_DESCENDING or 1 to sort in alphabetically descending order, or SCANDIR_SORT_NONE to return the result unsorted.
- context : It is an optional parameter which specifies the behaviorn of the stream.
Return Value: It returns an array of filenames on success, or False on failure.
Errors And Exceptions
- The scandir() function throws an error of level E_WARNING if the directory specified is not a directory.
- Doing a recursive scandir will on a directory which has many files will likely either slow down your application or cause a high rise in RAM consumption due to the large size of the generated array.
Below programs illustrate the scandir() function:
(  => .  => ..  => aboutus.php  => contact.php  => index.php  => terms.php )
Array (  => terms.php  => index.php  => contact.php  => aboutus.php  => ..  => . )
Array (  => .  => ..  => contact.php  => terms.php  => index.php  => aboutus.php )
Reference : http://php.net/manual/en/function.scandir.php
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.