Parsing a Directory
Parsing directory: scandir()
If you need to obtain the list of files in a directory (like ls
command does) you can use the scandir()
function.
A directory name (string) as input will get you an array of strings: filenames, directory names, also including special directories like β.β and β..β.
You can control the sorting with 2 constants. The default is an ascending sorting (alphabetical). With SCANDIR_SORT_DESCENDING
you can obtain string with a descending order:
Or, if you donβt want to sort at all, you can use SCANDIR_SORT_NONE
:
If you donβt want the β.β and β..β in your list, eliminating the first 2 items is wrong, because most of the time in alphabetical order β.β and β..β are in the 2 first positions. But, what if you have a filename that begins with β-β for example?
So my suggestion is to drop 2 elements by value. I have in mind 2 ways, the first one is looping through elements and skipping β.β and β..β. The most elegant way is using the array_diff()
function: