Listing files in alphabetical order (both files and folders)

How can I list all files and folders in a folder in alphabetical order using PHP?

I used the following files for a.txt , b.txt , c and d.txt , where c is the folder. The problem is that c displayed last, not after b.txt , because it is a folder.

I would also like to check if every file or folder.

 <?php $dir = opendir ("folders"); while (false !== ($file = readdir($dir))) { echo "$file <br />"; } ?> 
+4
source share
5 answers

The power of glob() here to help you. Just do:

 $dir = glob("folders/*"); 
+1
source

Just read the names in the array first, not immediately. Then sort the array and then do your output.

 <?php $dir = opendir ("folders"); while (false !== ($file = readdir($dir))) { $names[] = $file; } sort($names, SORT_STRING); foreach ($names as $name) { echo "$name <br />"; } ?> 
0
source

Just read the names in the array first, not immediately. Then sort the array and then do your output.

 <?php $files = array(); $dir = opendir ("folders"); while (false !== ($file = readdir($dir))) { $files[] = $file; } sort($files); foreach ($files as $f) echo "$f <br />"; ?> 
0
source

I would suggest the following code (no need for opendir, etc.)

 $entries = glob("*"); sort($entries); // This is optional depending on your os, on linux it works the way you want w/o the sort var_dump($entries); /* Output array(4) { [0]=> string(5) "a.txt" [1]=> string(5) "b.txt" [2]=> string(1) "c" [3]=> string(5) "d.txt" } */ 

For an integral part of your question: php functions "is_file" and "is_dir"

0
source
 $files = scandir('folders'); sort($files); foreach ($files as $file) { echo $file.'<br />'; } 
0
source

Source: https://habr.com/ru/post/1303043/


All Articles