The scandir Function
The scandir
function returns an array containing the names of files and directories from the specified folder. The first parameter is the path to the directory, and the second (optional) one is the sorting order. By default, sorting is performed in alphabetical ascending order.
Syntax
scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING): array
Example
Get a list of files and folders in the current directory:
<?php
$res = scandir('.');
print_r($res);
?>
Code execution result:
['.', '..', 'file1.txt', 'file2.txt', 'folder']
Example
Get a list of files in reverse order:
<?php
$res = scandir('.', SCANDIR_SORT_DESCENDING);
print_r($res);
?>
Code execution result:
['folder', 'file2.txt', 'file1.txt', '..', '.']
Example
Filter out the special entries '.' and '..'
using the array_diff
function:
<?php
$res = array_diff(scandir('.'), ['.', '..']);
print_r($res);
?>
Code execution result:
['file1.txt', 'file2.txt', 'folder']